2014-04-30 15 views
1

有沒有更好的方式來實現這樣的代碼而不使用全局參數? 我被教導說全局參數在Python中通常不是好東西。 你們覺得怎麼樣?你認爲全球參數可以嗎?替代在Tkinter中使用全局參數

這是我在那裏創建按鈕,如果不是我寫的是這樣的行代碼

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

該程序不會按要求工作。

有什麼建議嗎?

回答

3

buttonPushed功能是不必要的,因爲你可以在按鈕的command參數分配給root.destroy功能直接:

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

因此,你的代碼變得只是這:

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

注意:我也刪除了頂部的global rootmain,因爲它是不必要的。

3

您可以使用classes來編寫它,但正如iCodez所說,該按鈕現在是不必要的。

import Tkinter as tk 

class interface(tk.Frame): 
    def __init__(self, root): 
     tk.Frame.__init__(self, root) 

     self.root = root 
     message = tk.Label(self.root, text = "Hello World") 
     button = tk.Button(self.root, text="exit", command = self.buttonPushed) 

     message.pack() 
     button.pack() 

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

root = tk.Tk() 
inter = interface(root) 
root.mainloop() 
+1

班級是維護國家而不依賴全球國家的明智建議。但是你的實現有一些缺陷:接口構造函數不調用Frame構造函數,並且要訪問根目錄,你應該使用[iCodez](http://stackoverflow.com/a/23394942/)建議來使用root.destroy,在接口屬性中或在'buttonPushed'中依賴繼承'self.parent'。 – FabienAndre