我有两个按钮来存储打开的文件的路径,但我觉得这个过程是重复代码和使用全局。我想知道是否有一种方法可以在函数中执行返回并将返回值存储在变量中。在
这是我当前的代码
browsebutton = Button(root, text="This Week's Report", command=getFilecurrent)
browsebutton.grid(row=0, column=0)
browsebutton2 = Button(root, text="Last Week's Report", command=getFilepast)
browsebutton2.grid(row=0, column=1)
def getFilecurrent():
global path
# open dialog box to select file
path = filedialog.askopenfilename(initialdir="/", title="Select file")
def getFilepast():
global pathpast
# open dialog box to select file
pathpast = filedialog.askopenfilename(initialdir="/", title="Select file")
理想的情况是我想做这样的事情
^{pr2}$以某种方式存储变量的返回路径。这样,我只需要一个路径存储函数,而不必使用全局变量。在
通常,你想做的是个好主意。但在这种情况下是行不通的。调用
getFilepast
的代码不是您编写的,而是tkinter内部的代码,它不知道如何处理返回的路径。在通常的处理方法是创建一个类,并将值作为类的实例存储,如下所示:
现在,
pathy
的任何其他方法都可以看到self.pathpast
。在通常,您希望使这个类成为
tkinter.Frame
的子类,然后创建一个PathyFrame
而不是一个普通的Frame
。在大多数tkinter教程中都有这样的例子。在我想您可能还想创建一个单独的函数来处理两个按钮的回调。您可以使用
^{pr2}$partial
向函数传递一个额外的参数。但是在你的例子中,你有点卡住了,这两个函数之间唯一真正的区别是它们设置了哪个变量,并且没有好的方法来传递这些信息。然而,通常情况下,您希望实际执行操作,而不仅仅是将值存储在变量中。例如,假设我们想从报表文件中读取第一行,并将标签的内容设置为与之匹配。这样我们就可以考虑到:相关问题 更多 >
编程相关推荐