我想创建一个GUI,询问用户要打开哪两个文件。它呈现为条目和按钮(两次:每个文件一个),两者都在同一帧中,本身在root中。

由于我想要两次相同的东西,我定义了一个类,然后将它实例化两次,只是具有不同的网格位置。 它包含一个按钮调用的方法,用于更新Entry的值。

它工作但是当我select一个文件有任何按钮时,它在BOTH条目中写入文件路径。我希望它只在与实例对应的Entry中写入。

它看起来像一个类变量问题,但我的属性是在实例级别,所以它应该与实例区分开来。

这是我的代码:

from tkinter import Tk, Frame, Label, Button, Entry, filedialog as fd

class Selection:
    def __init__(self, master):
        self.load_button = Button(master, text="...", command=self.loadFile)     
        self.filedir = Entry(master, text = " ")    

    def loadFile(self):
        self.filename = fd.askopenfilename() 
        self.filedir.delete(0,"end")
        self.filedir.insert(0, self.filename)            

if __name__=='__main__': 

    #-------Defining the Root window
    root = Tk()
    root.geometry("1000x600+455+210")

    root.grid_columnconfigure(0, weight=1) 
    root.grid_columnconfigure(1, weight=2)
    root.grid_columnconfigure(2, weight=1)
    root.grid_rowconfigure(0, weight=1) 
    root.grid_rowconfigure(1, weight=1)
    root.grid_rowconfigure(2, weight=1)
    root.grid_rowconfigure(3, weight=1)

    #-------Defining the Frame  

    f2 = Frame(root, bg='#D5F4E4')

    f2.grid_columnconfigure(0, weight=1) 
    f2.grid_columnconfigure(1, weight=2)
    f2.grid_columnconfigure(2, weight=1)             
    f2.grid_rowconfigure(0, weight=1) 
    f2.grid_rowconfigure(1, weight=1)
    f2.grid_rowconfigure(2, weight=1)              
    f2.grid_rowconfigure(3, weight=1) 

    #-------Instantiation here (Defining the Widgets) 
    TexteL = Label(f2, text="Please select file L :")          
    TexteT = Label(f2, text="Please select file T :")

    k = Selection(f2)  
    j = Selection(f2) 

    #-------Grid everything
    f2.grid(row=1,column=1, sticky="nsew")

    TexteL.grid(row=0,column=1)
    TexteT.grid(row=2,column=1)

    k.load_button.grid(row=1, column=2) 
    k.filedir.grid(row=1, column=1, sticky='ew')

    j.load_button.grid(row=3, column=2) 
    j.filedir.grid(row=3, column=1, sticky='ew')

    root.mainloop()
分析解答

初始化Entry时,问题是由text = " "参数引起的。 text参数不用于设置要在Entry中显示的初始文本,而是设置textvariable参数。由于它设置为相同的" ",它将引用相同的内部variable。只需删除text = " "即可解决问题。