2012-03-26 253 views
1

我剛剛開始編程,並且正在製作井字棋程序。在我的程序中,我有一個顯示功能,它可以改變並確保輸入的內容是有效的,還有一個勝利檢查器。有沒有辦法可以將這兩個函數綁定到回車鍵?用Tkinter將一個按鈕綁定到兩個事件

喜歡的東西:

RowEnt.bind("<Return>", display, checkWin) 

回答

4

你可以嵌套另一個功能:)例如內部兩種功能:

def addone(num1): 
    num1=int(num1)+1 
def subtractone(num1): 
    num1=int(num1)-1 
def combine(): 
    addone(1) 
    subtractone(1) 

,如果你想叫他們兩個,你會簡單地使用combine()作爲你調用的函數:)

+0

我終於(大於1年後)接受了您的答案。感謝您幫助初學者程序員,我非常感謝。 – sinistersnare 2013-08-04 19:04:29

6

當綁定處理程序時,關鍵是通過add="+"。這告訴事件調度員將這個處理程序添加到處理程序列表中。沒有這個參數,新的處理程序會替換處理程序列表。

try: 
    import Tkinter as tkinter # for Python 2 
except ImportError: 
    import tkinter # for Python 3 

def on_click_1(e): 
    print("First handler fired") 

def on_click_2(e): 
    print("Second handler fired") 

tk = tkinter.Tk() 
myButton = tkinter.Button(tk, text="Click Me!") 
myButton.pack() 

# this first add is not required in this example, but it's good form. 
myButton.bind("<Button>", on_click_1, add="+") 

# this add IS required for on_click_1 to remain in the handler list 
myButton.bind("<Button>", on_click_2, add="+") 

tk.mainloop() 
+0

對於一些小部件和事件,這是一個很好的解決方案,但它不是點擊按鈕的好方法。你應該使用'command'屬性,這樣你就可以獲得鍵盤導航的好處以及其他一些微妙的東西。 – 2012-07-17 23:20:46

+0

關於鍵盤綁定的好處。據我所知,'command'一次只能使用一個函數,所以如果你不需要在運行時更改調用的函數,那麼IT Ninja的解決方案就很好。如果被調用函數列表發生變化,我會發布另一個解決方案,這可能會更好。 – Monkeyer 2012-07-19 20:38:04

+0

爲什麼沒有記錄add =「+」選項?!..花了我一個多小時才找到答案。 – 2013-09-25 13:52:14

1

在此,只有一個函數被稱作調用按鈕(invoke_mybutton)的直接結果和所有它的作用是產生一個虛擬事件<<MyButton-Command>>>。這個虛擬事件可以被命名爲任何東西,只要這個名字沒有被Tk使用。一旦到位,您可以整天使用add='+'選項綁定和解除綁定,您將獲得鍵盤綁定的好處,而Bryan Oakley指的就是這樣。

try: 
    import Tkinter as tkinter # for Python 2 
except ImportError: 
    import tkinter # for Python 3 

def invoke_mybutton(): 
    tk.eval("event generate " + str(myButton) + " <<MyButton-Command>>") 

def command_1(e): 
    print("first fired") 

def command_2(e): 
    print("second fired") 

tk = tkinter.Tk() 
myButton = tkinter.Button(tk, text="Click Me!", command=invoke_mybutton) 
myButton.pack() 
myButton.bind("<<MyButton-Command>>", command_1, add="+") 
myButton.bind("<<MyButton-Command>>", command_2, add="+") 
tk.mainloop() 
相關問題