所以我的意图是当用户点击其中一个按钮时,其余的其他按钮即使在点击时也不执行任何操作,所以基本上只有当用户点击它们时才停止按钮执行命令之前点击了另一个按钮,我不知道自己是否表达得很好,所以我很抱歉,如果我没有,但这是我的代码:
from tkinter import *
import random
screen = Tk()
ticket = random.randint(1,3)
def test():
def test1():
if ticket == button1:
button_1 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_1.grid(row=0, column=0, sticky="w")
else:
button_2 = Button(screen, text="+1", fg="white", bg="green", width=15, height=2)
button_2.grid(row=0, column=0, sticky="w")
def test2():
if ticket == button2:
button_3 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_3.grid(row=0, column=1, sticky="w")
else:
button_4 = Button(screen, text="+1", fg="white", bg="green", width=15, height=2)
button_4.grid(row=0, column=1, sticky="w")
def test3():
if ticket == button3:
button_5 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_5.grid(row=0, column=2, sticky="w")
else:
button_6 = Button(screen, text="+1", fg="white", bg="green", width=15, height=2)
button_6.grid(row=0, column=2, sticky="w")
ticket = random.randint(1,3)
button1 = Button(screen, text="1", fg="white", bg="blue", width=15, height=2, command=test1)
button1.grid(row=0, column=0, sticky="w")
button1 = 1
button2 = Button(screen, text="2", fg="white", bg="blue", width=15, height=2, command=test2)
button2.grid(row=0, column=1, sticky="w"+"e"+"n"+"s")
button2 = 2
button3 = Button(screen, text="3", fg="white", bg="blue", width=15, height=2, command=test3)
button3.grid(row=0, column=2, sticky="e")
button3 = 3
button1 = Button(screen, text="START", fg="black", bg="orange", width=25, height=2, command=test)
button1.grid(row=1, columnspan=3, sticky="w"+"e"+"n"+"s")
screen.mainloop()
答案 0 :(得分:4)
您可以将其他按钮的状态设置为DISABLED
以将其灰显并防止点击。这将是使用跟踪其实例的子类的理想位置。
from tkinter import *
import random
screen = Tk()
class MykoButton(Button):
instances = []
def __init__(self, master=None, **kwargs):
super().__init__(master, command=self.run, **kwargs)
self.instances.append(self)
def run(self):
for button in self.instances:
if button is not self:
button.config(state=DISABLED)
if random.randint(1,3) == 1:
self.config(text="RIP", fg="white", bg="red") # update the button
else:
self.config(text="+1", fg="white", bg="green")
def test():
for i in range(3):
button = MykoButton(screen, text="1", fg="white", bg="blue", width=15, height=2)
button.grid(row=0, column=i)
button1 = Button(screen, text="START", fg="black", bg="orange", width=25, height=2, command=test)
button1.grid(row=1, columnspan=3, sticky="w"+"e"+"n"+"s")
screen.mainloop()
另外,请注意我更改了您的代码以更新单击的按钮,而不是在其上面添加一个新按钮。