[英]Removing Tkinter Objects (created in a function) in a separate function
我需要能夠清除所有對象的tkinter窗口(帶有一個函數),並再次使用一個函數創建對象。 但是,我無法使用第二個功能訪問用第一個功能創建的對象。 我在下面重新創建了我的問題。
import tkinter
window = tkinter.Tk()
def create():
test = tkinter.Button(window, text="Example", command=delete)
test.place(x=75, y=100)
def delete():
test.place_forget()
create()
window.mainloop()
這將返回錯誤NameError: name 'test' is not defined
這是使用面向對象的結構的代碼外觀的快速樣本:
import tkinter as tk
class MyApp: # No need to inherit 'object' in Python 3
def __init__(self, root):
self.root = root
def create_button(self):
self.test_button = tk.Button(self.root,
text="Example",
command=self.delete_button)
self.test_button.place(x=75, y=100)
def delete_button(self):
self.test_button.place_forget()
def run(self):
self.create_button()
self.root.mainloop()
if __name__=='__main__':
root = tk.Tk()
app = MyApp(root)
app.run()
您創建一個MyApp
對象,該對象“擁有”按鈕,並具有明確對其所擁有的東西起作用的方法。 MyApp
對象的任何方法都可以通過自動發送的self
參數來引用各種小部件。
這比以前有很多代碼,老實說,對於您的代碼現在所做的事情,這是一個過大的殺傷力。 Malik使用global
的解決方案可能很好。 但是,如果您想添加更多的小部件,對其進行分層,使它們以更復雜的方式進行交互等,那么使用global
可能會引入難以發現的錯誤,並且使您難以置信於所發生的事情。
我見過的Tkinter的任何平凡用法都使用了類似於上面示例的面向對象樣式。
順便說一句,我不會創建delete
功能-創建按鈕后使用.config
方法設置命令會更好:
def create_button(self):
self.test_button = tk.Button(self.root, text="Example")
self.test_button.config(command=self.test_button.place_forget)
self.test_button.place(x=75, y=100)
使用.config
允許您設置命令,這些命令是您剛創建的按鈕的方法,將命令設置為按鈕實例化的一部分時將無法執行。
好吧,如果您使用兩個不同的函數,則將需要global
變量:
import tkinter
window = tkinter.Tk()
test = None
def create():
global test
test = tkinter.Button(window, text="Example", command=delete)
test.place(x=75, y=100)
def delete():
global test
test.destroy() # or place_forget if you want
window.after(5000, create) # button reappears after 5 seconds
create()
window.mainloop()
您的delete
功能無法破壞按鈕,因為它僅在create
功能中定義。 解決方法是創建兩個都可以訪問的全局變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.