首页 > 解决方案 > 为什么单击按钮时按钮不变色?

问题描述

我的代码没有给我想要的东西。当我点击它时,它会变成蓝色,直到松开,然后变回白色。我希望按钮在单击时改变颜色。因此,如果我单击它一次,我希望它变为蓝色。如果我再次单击它,从蓝色变为红色,然后对 6 种颜色(白色、蓝色、绿色、红色、橙色、黄色)执行此操作(白色是起始颜色)。

我是 python 编码的新手,老实说,这不是我的全部代码,所以我不知道它在做什么。我查看了代码,看看我能做什么。我也研究了我的问题堆,但仍然找不到答案。这是我认为有问题的代码的一部分。这只是(魔方)的第一面,所以无论响应/答案/更正如何,我也会对其他 5 面做出...

def enter_yellow_face():
    top,mid,btm=[0,0,0],[0,0,0],[0,0,0]
    bord = [top,mid,btm]
    counter = [0, 0, 0,
               0, 0, 0,
               0, 0, 0]

def change_color(x, b=bord):
    # seems like x is the square number out of the 9 squares
    #global counter
    r=x/3
    c=x%3
    if b[r][c] == 0:
        b[r][c]= 5
        bb[x].ss.configure(bg='white', activebackground='white')
        counter[x] = 0
        yellow_face[x] = 'w'

    elif counter[x] == 0:
        bb[x].ss.configure(bg='blue', activebackground='blue')
        counter[x] = 1
        yellow_face[x] = 'b'

    elif counter[x] == 1:
        bb[x].ss.configure(bg='red', activebackground='red')
        counter[x] = 2
        yellow_face[x] = 'r'

        ### keep following the cycle of white-yellow-red...
    elif counter[x] == 2:
        bb[x].ss.configure(bg='green', activebackground='green')
        counter[x] = 3
        yellow_face[x] = 'g'

    elif counter[x] == 3:
        bb[x].ss.configure(bg='orange', activebackground='orange')
        counter[x] = 4
        yellow_face[x] = 'o'

    elif counter[x] == 4:
        bb[x].ss.configure(bg='yellow', activebackground='yellow')
        counter[x] = 5
        yellow_face[x] = 'y'

    elif counter[x] == 5:
        bb[x].ss.configure(bg='white', activebackground='white')
        counter[x] = 0
        yellow_face[x] = 'w'

root = Tk()
root.title('Enter Yellow Face')

class Knop():
    """This is the docstring of the class"""

    def __init__(self, i, master=None):
        self.nummer = i
        self.row = i/3
        self.col = i%3
        def human_move():
            change_color(self.nummer)
        self.ss = Button(root, command=human_move, bg='yellow', activebackground='yellow', width=10, height=5)
        self.ss.grid(row=self.row, column=self.col)

        next_face = Button(root, text="Next Face",  command=root.destroy)
        next_face.grid(row=4, column=1)

bb = range(9)
for i in range(9):
    bb[i]= Knop(i, master=root)

mainloop()

我认为这会创建一个弹出窗口,其中显示的框在单击时会给我不同的颜色。就像从白色开始一样,当我单击 i 时,它会变为蓝色。如果我点击现在的蓝色框,它会变成红色。但是当我运行它时,一旦我松开点击它实际上会变成蓝色并变回白色。

标签: python

解决方案


推荐阅读