埃罗尔:_tkinter。Tcl错误: 错误的窗口路径名".!button"



所以今天我第一次尝试使用python类,以消除过度使用全局关键字。我试图创建一个tkinter窗口,其中,当我们点击一个按钮,它删除点击按钮,并将其替换为一个新的按钮。当我们再次点击它时,它会移除这个按钮并替换旧的(第一个)按钮,这应该会一直循环下去。

这是我写的代码:

# ================= 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 FilesPython310libtkinter__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 FilesPython310libtkinter__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 ---|
             ↓

ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ。

你正在破坏self.hi,然后试图在销毁按钮上调用place。一旦一个小部件被销毁,你就不能再使用它了。

如果你想继续循环按钮,不要破坏它们。因为你正在使用place,你可以使用self.hi.place_forget()self.he.place_forget()从视图中删除按钮而不破坏它们。

相关内容

最新更新