2013-06-30 22 views
1

我想写一个简单的'Simon'游戏,但是我在这里遇到了一个路障,并且诚实地不知道如何避开它。如何等待在Tkinter/Python中点击一定数量的按钮?

所以在这里,我做了一类在GUI上的四个按钮:

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 

然后我创建了这个类的四种情况blue, red, yellow, and green as bb, rb, yb,gb

一旦所有东西都打包到Tk()模块中,它将进入一个while循环,它将随机颜色附加到列表activecolors。我尝试使用下面的循环要等到按下的名单,只要在列表activecolors前两相比较,看看用户是正确的,至少包括:,

while len(pressed)<len(activecolors): 
        sleep(.25) 
        print('In the check loop') 
        bb.checkIfClicked() 
        rb.checkIfClicked() 
        yb.checkIfClicked() 
        gb.checkIfClicked() 

但是因为它卡住了,而里面循环中,程序无法判断该按钮是否已被点击。我认为将sleep方法添加到循环中会让代码有时间做其他事情(例如处理按钮点击),但事实并非如此。任何帮助表示赞赏。

Here is the link要完整的代码,如果你想看到它。尽管有一个警告:它不漂亮。

编辑: 我最终只是改变了代码,以检查列表只有在点击一个新的按钮后,告诉计算机的代码已准备就绪。如果您想查看Google文档,我已经更新了该文档。

回答

1

你让它太复杂了。该程序使用函数的部分内容来允许将一个变量传递给该函数,以便一个函数处理所有的点击(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() 
+0

感谢您抽出宝贵时间回答这篇文章,但我真的不明白您的代码。我最终只是让用户点击一个按钮来表示他们完成了重新创建序列,并且它完美无缺。我感谢你的努力! – dfreeze

相关问题