Reputation: 124
I am just getting started with programming and am making a Tic-Tac-Toe program. In my program I have a display function, which changes and makes sure what entered is valid, and a win checker. Is there a way that I can bind both of these functions to the enter key?
Something like:
RowEnt.bind("<Return>", display, checkWin)
Upvotes: 7
Views: 19358
Reputation: 6430
you could nest both functions inside of another function :) for example:
def addone(num1):
num1=int(num1)+1
def subtractone(num1):
num1=int(num1)-1
def combine():
addone(1)
subtractone(1)
if you wanted to call both of them, you would simply use combine()
as the function you call :)
Upvotes: 13
Reputation: 508
Here, only one function is called as a direct result of invoking the button (invoke_mybutton
) and all it does is generates a virtual event <<MyButton-Command>>>
. This virtual event can be named anything as long as the name is not being used by Tk already. Once that's in place, you can bind and unbind to <<MyButton-Command>>>
using the add='+'
option all day long and you'll get the benefits of keyboard bindings and such Bryan Oakley was referring to.
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()
Upvotes: 2
Reputation: 508
The key is passing add="+"
when you bind the handler. This tells the event dispatcher to add this handler to the handler list. Without this parameter, the new handler replaces the handler list.
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()
Upvotes: 23