Python 在单独的函数中删除Tkinter对象(在函数中创建)
我需要能够清除tkinter窗口中的所有对象(使用函数),并使用函数再次创建对象。但是,我无法使用第二个函数访问使用第一个函数创建的对象。我在下面重新创建了我的问题Python 在单独的函数中删除Tkinter对象(在函数中创建),python,tkinter,Python,Tkinter,我需要能够清除tkinter窗口中的所有对象(使用函数),并使用函数再次创建对象。但是,我无法使用第二个函数访问使用第一个函数创建的对象。我在下面重新创建了我的问题 import tkinter window = tkinter.Tk() def create(): test = tkinter.Button(window, text="Example", command=delete) test.place(x=75, y=100) def delete(): tes
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”未定义
如果使用两个不同的函数,则需要全局变量:
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
函数中定义。解决方法是创建一个全局变量,这两个变量都可以访问。下面是一个使用面向对象结构的代码外观的快速示例:
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
可能会引入难以发现的bug,并使你很难了解正在发生的事情
我所看到的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
可以设置作为刚刚创建的按钮的方法的命令,而当将命令设置为按钮实例化的一部分时,则无法执行此操作。使用类及其字段来存储稍后需要引用的对象。这与Tkinter无关,只是Python的基础知识:)这是怎么回事,下面的用户2880853?虽然我没有投反对票,但有点担心您将此作为一个没有任何警告的解决方案提供。可能最好显式地传递对对象的引用,即让test
成为create
的输出和delete
的输入,甚至最好在OO中编写整个代码-style@MalikBrahimi工作,但是错误的。当全局变量不是唯一的方法时,您不应该鼓励使用它们。这是一种糟糕的编程风格:涉及不必要的、不可维护的、隐式的耦合。标记为最佳答案,非常感谢你!是的,我有大量的代码,我只是写了一个简单的例子,以避免让你们读很多垃圾。我会按照你的建议重写代码,谢谢你。