[英]Tkinter removing a button from a running program
I was trying to create a function that creates and places a button on the screen (with grid) and the button's command would be removing itself (or any other widget) but I've failed to do so. 我试图创建一个函数,该函数创建一个按钮并将其放置在屏幕上(带有网格),并且该按钮的命令将自身(或任何其他小部件)移除,但是我没有这样做。
def a(self):
self.call_button = Tkinter.Button(self.root, text = "Call", command=self.b).grid(row = 5, column = 5)
def b(self):
self.call_button.destroy()
a creates the button and b removes it, but when i call on b it says "NoneType object has no attribute destroy" a创建按钮,b删除按钮,但是当我调用b时,它说“ NoneType对象没有属性销毁”
How do I go about doing this correctly? 如何正确执行此操作?
self.call_button
is set to the result of grid(row=5, column=5)
and not to the Button.. self.call_button
设置为grid(row=5, column=5)
而不是Button的结果。
from tkinter import *
class App(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.a()
def a(self):
self.call_button = Button(self, text = "Call", command=self.b)
self.call_button.grid(row=5, column=5) # This is fixing your issue
def b(self):
self.call_button.destroy()
root = Tk()
app = App(master=root)
app.mainloop()
In python, if you do foo=a().b()
, foo is given the value of b()
. 在python中,如果执行
foo=a().b()
,则foo的值为b()
。 So, when you do self.call_button = Button(...).grid(...)
, self.call_button is given the value of .grid(...)
, which is always None
. 因此,当您执行
self.call_button = Button(...).grid(...)
,self.call_button的值为.grid(...)
,始终为None
。
if you want to keep a reference to a widget, you need to separate your widget creation from your widget layout. 如果要保留对窗口小部件的引用,则需要将窗口小部件的创建与窗口小部件的布局分开。 This is a good habit to get into, since those are conceptually two different things anyway.
这是一个好习惯,因为从概念上讲,这是两种不同的事物。 In my experience, layout can change a lot during development, but the widgets I use don't change that much.
以我的经验,布局在开发过程中可能会发生很大变化,但是我使用的小部件并没有太大变化。 Separating them makes development easier.
将它们分开会使开发更加容易。 Plus, it opens the door for later if you decide to offer multiple layouts (eg: navigation on the left, navigation on the right, etc).
另外,如果您决定提供多种布局(例如:左侧导航,右侧导航等),它将为以后打开大门。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.