带有If语句的Tkinter Button

时间:2013-05-03 23:12:16

标签: button python-3.x tkinter conditional

这是我的第一个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

当我第一次点击任何按钮时,它会从空白按钮变为带有图像的按钮,当我再次点击它时它应该改变它的图像,但事实并非如此。如果有人想看到这里是要初始化photophoto0photo1的声明:

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

1 个答案:

答案 0 :(得分:1)

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

快速解决方案可以为每个Button小部件添加_photo引用,然后使用它与if语句中的photo进行比较:

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)]
相关问题