当我销毁按钮时,我得到错误_tkinter.TclError:错误的窗口路径名“!button”

2024-05-15 02:38:59 发布

您现在位置:Python中文网/ 问答频道 /正文

from tkinter import *
master=Tk()
class check:
def __init__(self,root):
    self.root=root

    self.b1=Button(root,text="Click me",command=self.undo)
    self.b2=Button(root,text="Again",command=self.click)

def click(self):
    self.b1.place(relx=0.5,rely=0.5)

def undo(self):
    self.b1.destroy()
    self.b2.place(relx=0.2,rely=0.2)
c=check(master)
c.click() 
master.mainloop()

这是我的密码。只有在使用destroy方法时,我才会得到_tkinter.TclError: bad window path name ".!button"错误。但当另一个按钮出现时,我想删除上一个按钮。我该怎么做


Tags: textselfmastertkinterdefcheckplacebutton
2条回答

你在干什么?当您单击“单击我”按钮(并调用self.undo方法,其中self.b1按钮被销毁),然后单击“再次”按钮(并调用self.click方法,尝试放置已销毁的self.b1按钮),您会得到错误,即该按钮不存在。当然,这不是因为你毁了它

看起来你想隐藏按钮。如果您打算这样做,那么您可以只使用.place_forget()方法(对于pack和grid窗口管理器也分别有.pack_forget().grid_forget()方法),隐藏小部件,但不销毁它,因此您可以在需要时再次恢复它

这是您的固定代码:

from tkinter import *


master = Tk()

class check:
    def __init__(self, root):
        self.root = root

        self.b1 = Button(root, text="Click me", command=self.undo)
        self.b2 = Button(root, text="Again", command=self.click)

    def click(self):
        self.b2.place_forget()
        self.b1.place(relx=0.5, rely=0.5)

    def undo(self):
        self.b1.place_forget()
        self.b2.place(relx=0.2, rely=0.2)

c = check(master)
c.click() 
master.mainloop()

我还可以给你一条关于实施的建议:

1)应根据PEP8 style编写代码;类应在CamelCase中命名

2)您应该从Tk(用法如下所示)、Toplevel(与Tk相同,但仅用于子窗口)、Frame类(与Tk几乎相同,但需要将该框架打包/网格/放置在窗口中)继承Tkinter应用程序类

3)最好在单独的功能中创建小部件(这有助于开发复杂的大型应用程序)

4)建议在创建窗口之前编写if __name__ == "__main__":条件(如果这样做,您将能够从其他模块导入此代码,在这种情况下窗口将不会打开)

以下是一个例子:

from tkinter import *


class Check(Tk):
    def __init__(self):
        super().__init__()

        self.create_widgets()
        self.click()

    def create_widgets(self):
        self.b1 = Button(self, text="Click me", command=self.undo)
        self.b2 = Button(self, text="Again", command=self.click)

    def click(self):
        self.b2.place_forget()
        self.b1.place(relx=0.5, rely=0.5)

    def undo(self):
        self.b1.place_forget()
        self.b2.place(relx=0.2, rely=0.2)

if __name__ == "__main__":
    Check().mainloop()

销毁undo(self)函数中的按钮b1后,tkinter将无法再访问它,并且在尝试将其放置在click(self)函数中的某个位置时会感到困惑。
若要使按钮b1仅在视觉上消失,您可以将其放置在窗口外,而不是将其破坏。
若要执行此操作,请更换按钮b1

self.b1.destroy()

self.b1.place(relx=-5, rely=0)

这将使按钮b1向左移动很远,看不到它。
调用click(self)函数时,按钮将重新出现,因为它将再次在窗口内移动

相关问题 更多 >

    热门问题