Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding one button to two events with Tkinter

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)
like image 388
sinistersnare Avatar asked Mar 26 '12 23:03

sinistersnare


2 Answers

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()
like image 53
Monkeyer Avatar answered Sep 29 '22 06:09

Monkeyer


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

like image 36
IT Ninja Avatar answered Sep 29 '22 05:09

IT Ninja