在Tkinter中将参数传递给方法

问题描述

我正在努力使我的方法正常工作。我曾考虑过使用lambda函数,该函数是我针对另一个问题所做的,并且确实有效,但是在这里似乎不起作用。我试图将函数更改为方法,由于某种原因,我的方法无法正常工作,因为它没有对树的引用。我试过使用lambda函数,尽管不起作用。

我的错误:

NameError: name 'tree' is not defined
Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.8/tkinter/__init__.py",line 1883,in __call__
    return self.func(*args)
  File "/home/bitvivaz/Documents/Software Development/Python/PasswordManager/mainFrame.py",line 54,in select
    print([tree.item(x) for x in tree.selection()])
NameError: name 'tree' is not defined

这是我的代码:

import tkinter as tk
import tkinter.ttk as ttk
from encryption import encrypted_password,decrypt_password
import backend as db


def get_credentials(tree):
    '''Retrieves all credentials from the database and inserts it into the tree widget'''
    for row in db.show_credentials():
        tree.insert("",'end',text=row['name'],values=(
            row['username'],decrypt_password(row['password'])))


class MainframeApp:
    def __init__(self,master=None):
        # build ui
        frame_main = ttk.Frame(master)
        frame_main.config(height='600',width='600')
        frame_main.grid()

        # Creates tree widget
        tree = ttk.Treeview(frame_main)

        tree["columns"] = ("one","two")

        tree.column("#0")
        tree.column("one")
        tree.column("two")

        tree.heading("#0",text="Website")
        tree.heading("one",text="Username")
        tree.heading("two",text="Password")

        tree.grid(padx='5',pady='5',rowspan='20')

        get_credentials(tree)

        tree.bind("<<TreeviewSelect>>",self.select,"+")

        button_add = ttk.Button(frame_main)
        button_add.config(text='Add')
        button_add.grid(column='1',padx='5',row='0')
        button_delete = ttk.Button(frame_main)
        button_delete.config(text='Delete')
        button_delete.grid(column='1',row='1')
        button_logout = ttk.Button(frame_main)
        button_logout.config(text='Logout')
        button_logout.grid(column='1',row='2')

        # Main widget
        self.mainwindow = frame_main

    def select(self,e):
        print([tree.item(x) for x in tree.selection()])

    def run(self):
        self.mainwindow.mainloop()


if __name__ == '__main__':
    root = tk.Tk()
    root.title("Password Manager")
    app = MainframeApp(root)
    app.run()

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)