0

这是我的第一个 Python 程序,我认为我的 if 语句是正确的,我可能会或可能不会,我不知道。我想要做的是,当单击 Tkinter 按钮时,我想要调用的函数来检查按钮上显示的图像,然后相应地更改其图像。

这是我的函数代码:

def update_binary_text(first,second):
    if buttonList[first][second]["image"] == photo:
        buttonList[first][second]["image"] = photo1

这是带有命令的 for 循环 [2d 按钮列表]:

for i in range (0,number):
        buttonList.append([])
        for j in range(0,number):
            print(i,j)
            buttonList[i].append(Button(game, borderwidth=0,highlightthickness=0, image=photo,command = lambda i=i, j=j: update_binary_text(i,j)))
            buttonList[i][j].grid(row=i*20,column=j*20)

问题是,当我运行它时,它打开得很好,但是当我单击所有按钮时,什么也没有发生。如果我取出 if 语句并只进行赋值,它会起作用,但我需要检查首先显示哪个图像。
有没有人有办法解决吗?


我刚刚遇到了另一个问题。我之前收到的解决方案工作得很好,并且更改了图像,但仅在第一次单击时。在那之后,它永远不会再改变。

这是代码:

def update_binary_text(first,second):
        #print("Called")
        if buttonList[first][second].image == photo:
                buttonList[first][second]["image"] = photo0
        elif buttonList[first][second].image == photo0:
                buttonList[first][second]["image"] = photo1

发生的情况是,当我第一次单击任何按钮时,它会从空白按钮变为带有图像的按钮,当我再次单击它时,它应该会更改其图像,但事实并非如此。如果有人想看这里是初始化photophoto0和的语句photo1

photo = PhotoImage(file ="blank.gif")
photo0 = PhotoImage(file="0.gif")
photo1 = PhotoImage(file="1.gif")
4

1 回答 1

1

我不知道 的类型是什么photo,但是如果您将其用作 Button 的选项,则它不能是字符串。问题是buttonList[first][second]["image"]返回一个字符串,而不是您在构造函数中使用它的对象。

一个快速的解决方案是添加_photo对每个 Button 小部件的引用,然后photo在 if 语句中使用它来比较:

def update_binary_text(first,second):
    if buttonList[first][second]._photo == photo:
        buttonList[first][second]["image"] = photo1

# ...

def create_button(i, j):
    button = Button(game, borderwidth=0, highlightthickness=0, image=photo,
                    command = lambda i=i, j=j: update_binary_text(i,j))
    button._photo = photo
    return button

buttonList = [[create_button(i, j) for j in range(number)] for i in range(number)]
于 2013-05-04T02:18:08.527 回答