2015-06-02 30 views
2

我一直在編寫一個年度數據驗證程序,需要一些用戶輸入,並決定去tkinter路由。我爲用戶輸入屏幕創建了一個界面,並且必須創建其他界面,但是我在選擇完成後會破壞窗口以及變量的全球化。使用tkinter來分配一個全局變量並銷燬gui

所以理想情況下,程序運行,彈出窗口,進行適當的屬性選擇,該按鈕上的文本被傳遞給「assign」函數,該函數創建一個全局變量用於我的程序中,並且窗口消失。

現在,這段代碼的運行會導致錯誤:「TclError:can not invoke」按鈕「command:application has been destroyed」。

如果我註釋掉「mGui.destroy()」這一行,我可以手動選擇一個按鈕並關閉窗口,但無論如何「DRN」變量都會傳遞給變量「x」!

import sys 
from Tkinter import * 

def assign(value): 
    global x 
    x = value 
    mGui.destroy() 

mGui = Tk() 
mGui.geometry("500x100+500+300") 
mGui.title("Attribute Selection Window") 

mLabel = Label(mGui, text = "Please select one of the following attributes to assign to the selected Convwks feature:").pack() 

mButton = Button(mGui, text = "CON", command = assign("CON")).pack() 
mButton = Button(mGui, text = "MS", command = assign("MS")).pack() 
mButton = Button(mGui, text = "DRN", command = assign("DRN")).pack() 

mGui.mainloop()  #FOR WINDOWS ONLY 

獎金的問題:把所有的按鈕在同一行中與它們之間的空間,同時保持它們的中心。

+0

這可能是http://stackoverflow.com/questions/5767228/tkin ter-button-not-working/5771787#5771787 –

回答

2

您的代碼存在的問題是您添加按鈕命令時無法調用函數。你不能寫Button(command=function()),你必須寫Button(command=function)。如果你想將參數傳遞到一個函數,你必須做這樣的:

相反的:

mButton = Button(mGui, text = "CON", command = assign("CON")).pack() 
mButton = Button(mGui, text = "MS", command = assign("MS")).pack() 
mButton = Button(mGui, text = "DRN", command = assign("DRN")).pack() 

你必須寫:

mButton = Button(mGui, text = "CON", command = lambda: assign("CON")).pack() 
mButton = Button(mGui, text = "MS", command = lambda: assign("MS")).pack() 
mButton = Button(mGui, text = "DRN", command = lambda: assign("DRN")).pack() 

如果你想要將所有按鈕放在同一行上,您可以使用此代碼:

import sys 
from Tkinter import * 

def assign(value): 
    global x 
    x = value 
    mGui.destroy() 

mGui = Tk() 
mGui.geometry("500x100+500+300") 
mGui.title("Attribute Selection Window") 

frame1 = Frame(mGui) 
frame1.pack() 

mLabel = Label(frame1, text = "Please select one of the following attributes to assign to the selected Convwks feature:").grid(row=0, column=0) 

frame2 = Frame(mGui) 
frame2.pack() 


mButton = Button(frame2, text = "CON", command = lambda: assign("CON")).grid(row=0, column=0, padx=10) 
mButton = Button(frame2, text = "MS", command = lambda: assign("MS")).grid(row=0, column=1, padx=10) 
mButton = Button(frame2, text = "DRN", command = lambda: assign("DRN")).grid(row=0, column=2, padx=10) 
mGui.mainloop()  #FOR WINDOWS ONLY 
+2

在我看來,使用'place'是不好的建議。 'pack'和'grid'都可以用來將按鈕放在一行中,隨着時間的推移,它們更容易使用和維護。 –

+0

這很好,非常感謝您的回覆。我的目的需要一個允許3-9個按鈕/選項的GUI,所以我爲每個人創建了函數,並在整個腳本中調用它們! –