Skip to main content
 首页 » 编程设计

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

2025年05月04日16Terrylee

有没有更好的方法可以在不使用全局参数的情况下实现这样的代码? 我被告知全局参数在 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 行,因为它是不必要的。