0

我在 Python 中不是很好,尤其是在使用类时。我编写此代码以使用浏览按钮设置条目值,问题是这样我应该为每个按钮创建一个浏览方法。有没有更简单的方法来解决这个问题?

from tkinter import *
from tkinter.filedialog import askopenfilename

class App:
    def __init__(self, parent):        
        self.button1 = Button(text = 'browse', command = self.browse1)     
        self.button1.grid (row = 0, column = 1)

        self.input_file1 = Entry(textvariable = self.browse1)
        self.input_file1.grid(row=0, column = 0)

        self.button2 = Button(text = 'browse', command = self.browse2)     
        self.button2.grid (row = 1, column = 1)

        self.input_file2 = Entry(textvariable = self.browse2)
        self.input_file2.grid(row=1, column = 0)

    def browse1(self):
        filename = askopenfilename(title = 'Select a file')
        self.input_file1.delete(0, END)
        self.input_file1.insert(0, filename)

    def browse2(self):
        filename = askopenfilename(title = 'Select a file')
        self.input_file2.delete(0, END)
        self.input_file2.insert(0, filename)

root = Tk()
root.geometry('900x550')
root.title('prove') 
MyApp = App(root)  
root.mainloop()

谢谢!

4

1 回答 1

1

如果你有这样的功能:

def browse(self, entry):
    filename = askopenfilename(title = 'Select a file')
    entry.delete(0, END)
    entry.insert(0, filename)

然后将您的定义更改为:

self.button1 = Button(text = 'browse', command = lambda: self.browse(self.input_file1))     
self.button1.grid (row = 0, column = 1)

self.input_file1 = Entry()
self.input_file1.grid(row=0, column = 0)

然后当按下按钮时,它调用调用该lambda函数的browse()函数,将相应的输入字段传递给函数,然后可以插入文本。

希望这是有道理的,如果您有任何问题,请告诉我:)

于 2020-05-01T11:44:57.357 回答