所以今天我第一次嘗試使用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 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 ---|
↓
???????????????????????????????????????這個
uj5u.com熱心網友回復:
您正在破壞self.hi,然后嘗試呼叫place被破壞的按鈕。一旦小部件被銷毀,您將無法再使用它。
如果您想繼續回圈按鈕,請不要破壞它們。由于您正在使用place,因此您可以使用self.hi.place_forget()和self.he.place_forget()從視圖中洗掉按鈕而不會破壞它們。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/476491.html
下一篇:在C 中多載不同型別
