我是python2.7和Tkinter的新GUI项目。我正在尝试创建一个新的框架,具体取决于用户选择的Radiobutton,如菜单。当我点击一个radiobutton它创建一个新的框架就像我想要的,但如果我继续点击相同的radiobutton,它将创建另一个框架,另一个框架,等等似乎无法弄清楚如何检查如果Radiobutton已被标记(仅点击一次)。
希望我清楚明白,感谢你的帮助!
class Books:
""" Books() is the main class for creating the whole interface """
def __init__(self):
""" Initialize the first function in class Books() """
self.library = "library.txt"
self.filepath = os.getcwd() + "/" + self.library
self.window = Tk()
self.window.title("Personal library")
self.window.wm_iconbitmap(default="myicon.ico")
userChoice = Frame(self.window, height = 1, bd = 1, relief = RIDGE)
userChoice.pack(side = TOP, pady = 10, padx = 5)
self.menuChoice = IntVar()
btAddBooks = Radiobutton(userChoice, text = "Add a new book to the library", value = 1, variable = self.menuChoice, command = self.processChoice)
btAddBooks.grid(row = 1, sticky = W)
btFindBooks = Radiobutton(userChoice, text = "Print info about a book", value = 2, variable = self.menuChoice, command = self.processChoice)
btFindBooks.grid(row = 2, sticky = W)
btPrintBooks = Radiobutton(userChoice, text = "Print all book titles in library", value = 3, variable = self.menuChoice, command = self.processChoice)
btPrintBooks.grid(row = 3, sticky = W
def processChoice(self):
""" Used to handle user choice of Radiobuttons """
if self.menuChoice.get() == 1:
self.processAddBooks()
elif self.menuChoice.get() == 2:
self.processFindBook()
elif self.menuChoice.get() == 3:
self.processShowBooks(self.filepath)
def processAddBooks(self):
""" Add a new book to the library. """
# Create a new frame
questions = Frame(self.window, height = 1, bd = 1, relief = SUNKEN)
questions.pack(fill = X, pady = 10, padx = 5)
# Do stuff with frame here...
答案 0 :(得分:0)
好吧,如果您一次只需要打开一个帧,则可以在实例化新帧之前在前一帧上调用frame.destroy()
。但是,这种方法需要在第一次选择其中一个按钮时为Tkinter初始化destroy
,否则您将收到错误。为了我的目的,我刚刚用一个destroy
方法创建了一个一次性类,然后使用该类的实例作为绑定到该变量的占位符,直到第一次创建Toplevel小部件。如果您希望同时打开多个框架,只是不要重复相同的选项,请尝试为每个框架使用不同的变量名称,并仅创建框架if not frame.winfo_exists()
- 尽管我并非100%确定在第一次创建帧之前,这不会容易受到分配给该变量的占位符的相同问题的影响。如果需要,占位符类需要winfo_exists()
return False
方法。