Python 2.7 如何在Tkinter/Python中等待单击一定数量的按钮?
我试图写一个简单的“西蒙”游戏,但我遇到了一个障碍,老实说,我不知道如何绕过它 在这里,我为GUI中的四个按钮创建了一个类:Python 2.7 如何在Tkinter/Python中等待单击一定数量的按钮?,python-2.7,tkinter,Python 2.7,Tkinter,我试图写一个简单的“西蒙”游戏,但我遇到了一个障碍,老实说,我不知道如何绕过它 在这里,我为GUI中的四个按钮创建了一个类: class button: def buttonclicked(self): self.butclicked= True def checkIfClicked(self): if self.butclicked== True: global pressed
class button:
def buttonclicked(self):
self.butclicked= True
def checkIfClicked(self):
if self.butclicked== True:
global pressed
pressed.append(self.color)
self.butclicked= False
def __init__(self, color1):
self.color= color1
self.button= tk.Button(root, text=' '*10, bg= self.color, command= self.buttonclicked)
self.button.pack(side='left')
self.butclicked=False
然后,我在蓝色、红色、黄色和绿色中创建了这个类的四个实例,分别为bb、rb、yb、
和gb
一旦所有内容都打包到Tk()模块中,它就会进入一个while循环,在ActiveColor列表中添加一个随机颜色。我尝试使用以下循环等待,直到按下的列表至少与列表ActiveColor一样长,然后比较两者,以查看用户是否正确:
while len(pressed)<len(activecolors):
sleep(.25)
print('In the check loop')
bb.checkIfClicked()
rb.checkIfClicked()
yb.checkIfClicked()
gb.checkIfClicked()
当len(按下)时,你把它弄得太复杂了。该程序使用来自functiontools的部分函数来允许将变量传递给函数,以便一个函数处理所有单击(Python 2.7)
你把事情弄得太复杂了。该程序使用来自functiontools的部分函数来允许将变量传递给函数,以便一个函数处理所有单击(Python 2.7)
谢谢你花时间回复这篇文章,但我真的不太懂你的代码。最后,我只是让用户点击一个按钮,说他们已经完成了序列的重新创建,效果非常好。谢谢你的努力!谢谢你花时间回复这篇文章,但我真的不太懂你的代码。最后,我只是让用户点击一个按钮,说他们已经完成了序列的重新创建,效果非常好。谢谢你的努力!
from Tkinter import *
from functools import partial
class ButtonsTest:
def __init__(self):
self.top = Tk()
self.top.title('Buttons Test')
self.top_frame = Frame(self.top, width =400, height=400)
self.colors = ("red", "green", "blue", "yellow")
self.colors_selected = []
self.num_clicks = 0
self.wait_for_number = 5
self.buttons()
self.top_frame.grid(row=0, column=1)
Button(self.top_frame, text='Exit',
command=self.top.quit).grid(row=2,column=1, columnspan=5)
self.top.mainloop()
##-------------------------------------------------------------------
def buttons(self):
for but_num in range(4):
b = Button(self.top_frame, text = str(but_num+1),
command=partial(self.cb_handler, but_num))
b.grid(row=1, column=but_num+1)
##----------------------------------------------------------------
def cb_handler( self, cb_number ):
print "\ncb_handler", cb_number
self.num_clicks += 1
this_color = self.colors[cb_number]
if (self.num_clicks > self.wait_for_number) \
and (this_color in self.colors_selected):
print "%s already selected" % (this_color)
self.colors_selected.append(this_color)
##===================================================================
BT=ButtonsTest()