【问题标题】:Tkinter Button with an If statement带有 If 语句的 Tkinter 按钮
【发布时间】:2013-05-03 23:12:15
【问题描述】:

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

【问题讨论】:

    标签: button python-3.x tkinter conditional


    【解决方案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)]
    

    【讨论】:

    • 谢谢先生!!我用 ._photo 尝试过,但没有运气,而是尝试了 button.image,最终成功了。谢谢!
    • @vap 是的,那是因为你也必须以相反的方式实现(一个 if 语句,其中 if .photo == photo1image 选项设置为 photo)。跨度>
    • 哦!现在我明白为什么会这样了。再次感谢!
    猜你喜欢
    • 2018-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-25
    • 2019-06-02
    • 2021-07-03
    相关资源
    最近更新 更多