我想在单击按钮时执行任务。我该怎么做呢?我的代码是:
from tkinter import *
root = Tk()
def hey():
if bt1 is clicked:
#do something
if bt2 is clicked:
#do something
#some piece of code
bt1 = Button(root, text = 'yes', command = hey)
bt2 = Button(root, text = 'no', command = hey)
bt1.pack()
bt2.pack()
根据您共享的内容,您可以使用参数在按钮中传递标志,例如
bt1 = Button(root, text = 'yes', command =lambda: hey(True))
bt2 = Button(root, text = 'no', command =lambda: hey(False))
在代码中,你可以这样做,
def hey(which): # `which` decides which statement to be followed
if which:
#do something
else:
#do something
from tkinter import *
root = Tk()
def func():
#common code for both buttons
def hey(arg):
if arg == 1:
print("button 1 used")
func() #mention arguments if required
elif arg == 2:
print("button 2 used")
func()
bt1 = Button(root, text = 'yes', command=lambda: hey(1))
bt2 = Button(root, text = 'no', command=lambda: hey(2))
# you can add more buttons to do the same function,use hey(n)
bt1.pack()
bt2.pack()