簡體   English   中英

我在銷毀按鈕時收到錯誤 _tkinter.TclError: bad window path name “.!button”

[英]I get the error _tkinter.TclError: bad window path name “.!button” when I destroy the button

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()

這是我的代碼。 只有當我使用銷毀方法時,我才會收到_tkinter.TclError: bad window path name ".!button"錯誤。 但是當另一個按鈕出現時,我想刪除上一個按鈕。我該怎么辦?

你在做什么? 當您單擊“單擊我”按鈕(並調用self.undo方法,其中 self.b1 按鈕被銷毀)然后單擊“再次”按鈕(並調用self.click方法,該方法試圖將已銷毀的位置self.b1 按鈕),您會收到錯誤消息,即該按鈕不存在。 當然,不是因為你毀了它。

看起來您打算隱藏按鈕。 如果您打算這樣做,那么您可以只使用.place_forget()方法(還有.pack_forget().grid_forget()方法分別用於 pack 和 grid window 管理器),隱藏小部件,但不破壞它,因此您可以在需要時再次恢復它。

這是您的固定代碼:

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風格編寫代碼; 類應以CamelCase命名。

2)您應該從 Tk 繼承您的 Tkinter 應用程序類(用法如下所示)頂層(與 Tk 相同,但僅用於子窗口),框架 class(幾乎與 Tk 相同,但您需要打包/網格/將該框架放置在窗口中)。

3) 最好在單獨的 function 中創建小部件(這有助於開發復雜的大型應用程序)。

4) 建議在創建 window 之前編寫if __name__ == "__main__":條件(如果這樣做,您將能夠從其他模塊導入此代碼,並且 window 在這種情況下不會打開)。

這是一個例子:

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) function tkinter 中銷毀按鈕 b1 后,您將無法再訪問它,並且當您嘗試將其放置在click(self) ZC1C425268E68385D1AB5074C17A94F1 中的某處時會感到困惑。
要使按鈕 b1 僅在視覺上消失,您可以將其放置在 window 之外,而不是破壞它。
為此更換

self.b1.destroy()

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

這會將按鈕 b1 移到最左側,無法看到它。
當調用click(self) function 時,按鈕會重新出現,因為它會再次移動到 window 內部。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM