Skip to main content
 首页 » 编程设计

python之如何在 tkinter 中重置按钮上的图像

2025年05月04日15Terrylee

我在 Internet 上四处搜索,似乎无法找到删除按钮上的图像的方法。我想知道是否有办法删除图像但保留按钮或任何其他简单的快速修复。这是我的一些代码供引用。

def breakcup(): 
    if firstroom.cupnotbroken: 
        messagebutton.config(text="You broke the cup, and the key was inside the cup.") 
        cup.config(image=photo4) 
        firstroom.cupnotbroken=False 
    else: 
        cup.config(image=None, state=DISABLED) 
        messagebutton.config(text="You picked up the key") 
        firstroom.keynotfound=False 

显然,image=None 不起作用,但这是我能找到的最接近的解决方案。

root = Toplevel(bob) 
root.geometry("640x360+200+250") 
root.resizable(0, 0) 
app = Room1(root) 

窗口是使用 Toplevel(parent) 函数创建的。只是为了澄清。

请您参考如下方法:

这似乎是 Tkinter 的一个错误。从我的实验来看,将图像设置为空字符串而不是 None 似乎是安全的:

messagebutton.configure(image="") 

这是可行的,因为在底层的 tcl/tk 解释器中“一切都是字符串”。也就是说,与 None 等效的 tcl 是 ""。当您指定一个空字符串时,Tkinter 将该空字符串传递给 tcl,tcl 将其解释为“无图像”。