Errror: _tkinter.TclError: bad window path name ".!button"

Errror: _tkinter.TclError: bad window path name ".!button"

所以今天我第一次尝试使用python 类,去除对global关键字的过度使用。我正在尝试创建一个 tkinter window,在其中,当我们单击一个按钮时,它会删除单击的按钮并将其替换为新按钮。当我们再次单击它时,它会删除此按钮并替换旧的(第一个)按钮,这应该会循环...

这是我编写的代码:

# ================= Importing Modules ===================
from tkinter import *
import tkinter as tk

# ====================================================
class Test():
 
    # ============= Play Button Click =============
    def fun1(self):
            self.hi.destroy()
            self.he.place(x=350,y=340)

    # ============ Pause Button Click =============
    def fun2(self):
            self.he.destroy()
            self.hi.place(x=350,y=340)
            
    # ============ Player Window ================
    def __init__(self):
        self.root = Tk()
        self.root.geometry('700x400')
        self.root.resizable(0,0)
        self.root["bg"] = "black"
        
        self.hi = tk.Button(self.root, text="button 1", bg="white", bd=0, command=lambda: self.fun1() , relief=RIDGE)
        self.hi.place(x=350,y=340)

        self.he = tk.Button(self.root, text="button 2", bg="white", bd=0,  command=lambda: self.fun2() , relief=RIDGE)
        self.root.mainloop()

# ============== Calling ===========

if __name__ == '__main__':
        Test()

    

但不幸的是,我得到的不是预期的输出:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Program Files\Python310\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "C:/XXX/XXX/Desktop/test.py", line 29, in <lambda>
    self.he = tk.Button(self.root, text="button 2", bg="white", bd=0,  command=lambda: self.fun2() , relief=RIDGE)
  File "C:/XXX/XXX/Desktop/test.py", line 16, in fun2
    self.hi.place(x=350,y=340)
  File "C:\Program Files\Python310\lib\tkinter\__init__.py", line 2477, in place_configure
    self.tk.call(
_tkinter.TclError: bad window path name ".!button"

所以我的问题是:

doubt1 = Any idea what I am doing wrong?
doubt2 = Or isn't this possible?
if doubt1 or doubt2:
   Please explain it...
elif:
   Please tell me a better alternative or idea, how to do this efficiently.
else:
   Note: I have researched so many questions. Nothing helped me out. Especially ---|
                                                                                   ↓

ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ=]

=14=]

您正在销毁 self.hi,然后尝试在销毁的按钮上调用 place。一旦小部件被销毁,您将无法再使用它。

如果您想继续循环按钮,请不要破坏它们。由于您使用的是 place,因此您可以使用 self.hi.place_forget()self.he.place_forget() 从视图中删除按钮而不破坏它们。