【问题标题】:Python 2.7: Widget Doesn't Destroy When Radiobutton is Clicked More Than OncePython 2.7:多次单击单选按钮时,小部件不会破坏
【发布时间】:2018-08-02 05:51:36
【问题描述】:

我的代码显示了 FunctionAllocation 标签和两个单选按钮,一旦单击一个单选按钮,它就会显示主题 ID 标签及其输入栏。单击返回键后,所有小部件都将被销毁并出现新消息。

如果单击单选按钮一次,一切都会顺利进行。但是,如果我单击一个单选按钮,然后单击另一个单选按钮,尽管有 .destroy() 命令,但主题 ID 标签及其输入栏不会消失。

无论单选按钮被按下多少次和多少次,我如何确保小部件消失?

非常感谢您!

from Tkinter import *

class Application(Frame):
    #Initial Settings
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.radioButtons()

    #Place Initial Buttons
    def radioButtons(self):
        #Variable to tie two radio buttons
        self.tieVar1 = StringVar()

        #Text before FA buttons
        self.buttonLabel1 = Label(root, text="Function Allocation:")
        self.buttonLabel1.place(relx=0.35, rely=0.3, anchor=CENTER)

        #Two Radio FA buttons
        self.radio1 = Radiobutton(text = "FA_F", variable=self.tieVar1, value="FA1", command=lambda: self.addSubject())
        self.radio1.place(relx=0.5, rely=0.3, anchor=CENTER)
        self.radio2 = Radiobutton(text = "FA_I", variable=self.tieVar1, value="FA2", command=lambda: self.addSubject())
        self.radio2.place(relx=0.6, rely=0.3, anchor=CENTER)

    def addSubject(self):
        #Text before ID entry bar
        self.buttonLabel2 = Label(root, text="Subject ID:")
        self.buttonLabel2.place(relx=0.35, rely=0.6, anchor=CENTER)

        #ID entry bar
        self.myEntry = Entry()
        self.myEntry.place(relx=0.5, rely=0.6, anchor=CENTER)
        self.contents = StringVar()
        self.contents.set("Sample Text")
        self.myEntry["textvariable"] = self.contents
        self.myEntry.bind('<Key-Return>', self.reset_contents)

    #Action when return key pressed after typing subject ID
    def reset_contents(self, event):
        #Delete all 
        self.buttonLabel1.destroy()
        self.buttonLabel2.destroy()
        self.radio1.destroy()
        self.radio2.destroy()
        self.myEntry.destroy()

        #Setting up new window
        self.setActions()

    def setActions(self):
        Label(text="Done!", font=("Times", 10, "bold")).place(relx=0.5, rely=0.5, anchor=CENTER)

    #Final settings to keep window open
    root = Tk()
    root.geometry("1000x400")
    app = Application(master=root)
    app.mainloop()

【问题讨论】:

  • 你做过调试吗?为什么你认为它没有被摧毁?你有错误吗?你确定要调用destroy方法吗?您确定在正确的小部件上调用它吗?

标签: python tkinter


【解决方案1】:

每次单击该按钮时,您都会创建一个新的标签和条目。但是,您的破坏只会破坏最后一个创建的。最简单的解决方法是简单地检查标签是否已经创建:

def addSubject(self):
    if hasattr(self, 'buttonLabel2'):
        return # abort this method if the Label is already created
    # rest of your method 

不相关,但是如果您希望您的 Radiobuttons 以空白状态而不是三态开始,您需要像这样初始化 StringVar:

self.tieVar1 = StringVar(value='Novel')

【讨论】:

    猜你喜欢
    • 2023-04-07
    • 1970-01-01
    • 2016-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 2021-11-08
    相关资源
    最近更新 更多