Python Tkinter 从正在运行的程序中删除按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17673662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:51:55  来源:igfitidea点击:

Tkinter removing a button from a running program

pythonuser-interfacewidgettkinterdestroy

提问by Shay

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?

我该如何正确地做到这一点?

回答by joente

self.call_buttonis set to the result of grid(row=5, column=5)and not to the Button..

self.call_button被设置为的结果grid(row=5, column=5)而不是按钮..

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()

回答by Bryan Oakley

In python, if you do foo=a().b(), foo is given the value of b(). So, when you do self.call_button = Button(...).grid(...), self.call_button is given the value of .grid(...), which is always None.

在 python 中,如果你这样做foo=a().b(), foo 的值是b()。因此,当您这样做时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).

如果要保留对小部件的引用,则需要将小部件创建与小部件布局分开。这是一个很好的习惯,因为无论如何这在概念上是两个不同的东西。根据我的经验,布局在开发过程中会发生很大变化,但我使用的小部件变化不大。将它们分开使开发更容易。此外,如果您决定提供多种布局(例如:左侧导航、右侧导航等),它会为以后打开大门。