使用Tkinter将一个按钮绑定到两个事件

sin*_*are 3 python events tkinter

我刚刚开始编程并正在制作一个Tic-Tac-Toe程序.在我的程序中,我有一个显示功能,它会改变并确保输入的内容是有效的,还有一个胜利检查器.有没有办法可以将这两个函数绑定到回车键?

就像是:

RowEnt.bind("<Return>", display, checkWin)
Run Code Online (Sandbox Code Playgroud)

Mon*_*yer 11

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()
Run Code Online (Sandbox Code Playgroud)

  • 为什么没有记录 add="+" 选项?!.. 我花了一个多小时才找到你的答案。 (3认同)

IT *_*nja 6

你可以将两个函数嵌套在另一个函数中:)例​​如:

def addone(num1):
    num1=int(num1)+1

def subtractone(num1):
    num1=int(num1)-1

def combine():
    addone(1)
    subtractone(1)
Run Code Online (Sandbox Code Playgroud)

如果你想要同时调用它们,你只需使用combine()你调用的函数:)