【问题标题】:Tkinter removing a button from a running programTkinter 从正在运行的程序中删除一个按钮
【发布时间】:2013-07-14 11:08:04
【问题描述】:

我试图创建一个函数来创建一个按钮并将其放置在屏幕上(带网格),并且该按钮的命令将自行删除(或任何其他小部件),但我没有这样做。

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 创建按钮,b 删除它,但是当我调用 b 时,它说“NoneType 对象没有属性破坏”

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

【问题讨论】:

    标签: python user-interface widget tkinter destroy


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      在 python 中,如果您执行foo=a().b(),则 foo 将被赋予 b() 的值。因此,当您执行self.call_button = Button(...).grid(...) 时,self.call_button 的值将被赋予.grid(...),始终为None

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-06
        • 2021-11-18
        • 2012-12-21
        • 1970-01-01
        • 1970-01-01
        • 2015-01-23
        • 2014-01-10
        • 2011-04-11
        相关资源
        最近更新 更多