Python将变量从filedialog传递到mainloop
我想用python为一个程序构建一个GUI 对于这个程序,我有一个配置文件,我希望能够打开并传递给程序。简而言之,我现在拥有的是:Python将变量从filedialog传递到mainloop,python,tkinter,Python,Tkinter,我想用python为一个程序构建一个GUI 对于这个程序,我有一个配置文件,我希望能够打开并传递给程序。简而言之,我现在拥有的是: from tkinter import * from tkinter import filedialog def openfile(): filename = filedialog.askopenfilename(parent=root) lst = list(open(filename)) def savefile(): filename = fi
from tkinter import *
from tkinter import filedialog
def openfile():
filename = filedialog.askopenfilename(parent=root)
lst = list(open(filename))
def savefile():
filename = filedialog.asksaveasfilename(parent=root)
root = Tk()
methodmenu = Menu(menubar,tearoff=0)
methodmenu.add_command(label="Open",command=openfile)
methodmenu.add_command(label="Save",command=savefile)
menubar.add_cascade(label="Config",menu=methodmenu)
label = Label(root,text="show config here")
label.place(relx=0.5,rely=0.5,anchor=CENTER)
root.config(menu=menubar)
root.mainloop()
所以openfile函数读取列表中的配置文件,这就是我想要的。现在,如何将其传递到我的主循环?例如,如果我想在根窗口的标签中显示从该文件读取的信息
在添加命令之前,我尝试使用openfilelst定义openfile并声明lst=[],但这似乎是错误的,因为程序在启动时立即调用openfilelst,lst在标签中为空
一般来说,我不熟悉python和GUI,这显然不像fortran那样工作…只需返回在openfile中读取的配置文件的内容,并将文件的内容传递给标签构造函数。请注意,由于标签构造函数采用单个字符串,因此必须将列表转换为:
def openfile():
filename = filedialog.askopenfilename(parent=root)
return list(open(filename))
...
config_file_contents = ''.join(openfile())
label = Label(root, text=config_file_contents)
label.place(...)
或者,如果要单独显示配置列表中的每个元素,可以循环访问配置文件列表中的每个元素,并将每个元素传递到它自己的单独标签对象中:
非常感谢你。对于您的第一个解决方案,它可以工作,但它会在启动时立即自动调用openfile函数..?是的,@Fl.pf.,它可以。运行代码时,会立即调用openfile。这不是你想要的吗?也许您希望保存openfile的返回值,并在以后使用它。如果是这样,只需将其分配给一个变量即可。是的,我希望openfile仅在我单击Cascade中的“打开”按钮时执行。我也不能再次调用“打开”,当我单击按钮时不会发生任何事情
for config in openfile():
label = Label(root, text=config)
label.place(...)