我的代码显示FunctionAllocation标签和两个单选按钮,单击一个单选按钮后,显示Subject 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()
答案 0 :(得分:0)
每次单击该按钮都将创建一个新的标签和条目。但是,您的销毁只会销毁最后创建的一个。最简单的解决方法是仅检查Label是否已创建:
def addSubject(self):
if hasattr(self, 'buttonLabel2'):
return # abort this method if the Label is already created
# rest of your method
不相关,但是如果您希望单选按钮以空白状态而不是三态开始,则需要像下面这样初始化StringVar:
self.tieVar1 = StringVar(value='Novel')