1

我正在尝试编写一个简单的“西蒙”游戏,但我在这里遇到了障碍,老实说不知道如何绕过它。

所以在这里,我为 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()

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

这是完整代码的链接,如果您想查看它。不过有个警告:它不漂亮。

编辑:我只是在单击新按钮后才更改代码以检查列表,告诉计算机代码已准备好。如果您想查看,我已经更新了 Google 文档。

4

1 回答 1

1

你把它弄得太复杂了。该程序使用函数工具的 partial 来允许将变量传递给函数,因此一个函数可以处理所有点击(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()
于 2013-07-02T01:23:11.143 回答