python - 在 Tkinter 中使用全局参数的替代方法

标签 python tkinter

有没有更好的方法可以在不使用全局参数的情况下实现这样的代码? 我被告知全局参数在 python 中通常不是一件好事。 你们有什么感想?您认为全局参数可以吗?

这是代码

import Tkinter as tk


def main():    
    global root

    root = tk.Tk()   # parent window


    message = tk.Label(root, text = "Hello World") 
    message.pack() 

    buttton = tk.Button(root, text="exit", command = buttonPushed) 
    button.pack()

    tk.mainloop()  


def buttonPushed():
    global root
    root.destroy()

main()

在我创建按钮的那一行,如果我改为这样写的话;

buttton = tk.Button(root, text="exit", command = buttonPushed(root)) 
button.pack()


def buttonPushed(root):
    root.destroy()    

程序将无法按要求运行。

有什么建议吗?

最佳答案

您的 buttonPushed 函数是不必要的,因为您可以将按钮的 command 参数直接分配给 root.destroy 函数:

button = tk.Button(root, text="exit", command=root.destroy) 

因此,您的代码就变成了这个1:

import Tkinter as tk

def main():    

    root = tk.Tk()

    message = tk.Label(root, text="Hello World") 
    message.pack() 

    button = tk.Button(root, text="exit", command=root.destroy) 
    button.pack()

    tk.mainloop()  

main()

1注意:我还删除了 main 顶部的 global root 行,因为它是不必要的。

关于python - 在 Tkinter 中使用全局参数的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23394815/

相关文章:

Python - 在类中初始化 tkinter,当在另一个类中需要另一个 gui 时会发生什么?

python - tkinter Python 中的按钮位置(网格)

python - 如何读取 Dropbox 上超过 2000 个文件的路径?

python - 这两个进口之间有什么区别吗?

python - 重启程序 tkinter

python - Tkinter:将图标添加到菜单项中

Python - Tkinter(ttk)动态创建一个进度条,其自身的值会发生变化

python - 使用 importlib 导入 pyarmor 混淆代码

python psutil psutil.get_process_list() 错误

python - Pytesseract No such file or directory 错误