【问题标题】:Python passing variables from filedialog to mainloopPython将变量从filedialog传递到mainloop
【发布时间】:2018-04-18 14:37:10
【问题描述】:

我想在 python 中为一个程序构建一个 GUI。

对于这个程序,我有一个我希望能够打开并传递给程序的配置文件。我现在(简而言之)是这样的:

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 函数读取列表中的配置文件(这是我想要的)。现在,我如何将它传递给我的主循环?例如,如果我想在我的root 窗口中的Label 中显示从该文件读取的信息?

我尝试在添加命令之前用openfile(lst) 定义openfile() 并声明lst=[""],但这似乎是错误的(程序在启动时立即调用openfile(lst),lst 在标签中为空)。

一般来说,我是 python 和 GUI 的新手,这显然不像 fortran 那样工作......

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    只需返回您在openfile 中读取的配置文件的内容,并将文件内容传递给Label 构造函数。请注意,由于 Label 构造函数采用单个字符串,因此您必须将列表转换为:

    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(...)
    

    或者,如果您想单独显示配置列表中的每个元素,您可以遍历配置文件列表中的每个元素,并将每个元素传递到它自己单独的 Label 对象中:

    for config in openfile():
        label = Label(root, text=config)
        label.place(...)
    

    【讨论】:

    • 非常感谢。使用您的第一个解决方案它可以工作,但它会在启动时立即自动调用 openfile() 函数..?
    • 是的,@Fl.pf.,确实如此。当你运行你的代码时,openfile 会立即被调用。这不是你想要的吗?或许您想保存openfile 的返回值并在以后使用它。如果是这样,只需将其分配给一个变量。
    • 是的,我希望 openfile 仅在单击级联中的 Open 按钮时才执行
    • 我也无法再次拨打Open,点击按钮时什么也没有发生
    猜你喜欢
    • 2021-11-18
    • 2016-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    相关资源
    最近更新 更多