Tkinter 单选按钮生成框架
我刚接触用Python 2.7和Tkinter做图形界面(GUI)的事情。我想根据用户选择的单选按钮(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...
1 个回答
0
好吧,如果你只想同时打开一个窗口,你可以在创建新窗口之前,先用 frame.destroy()
来关闭之前的窗口。不过,这样做有个前提,就是在第一次点击按钮的时候,得有东西可以让 Tkinter 去 destroy
,否则会报错。为了我的需求,我创建了一个临时的类,这个类里面有个 destroy
方法什么都不做,然后用这个类的一个实例作为占位符,直到我第一次创建 Toplevel 窗口。如果你想同时打开多个窗口,但不想打开相同的选项,可以为每个窗口使用不同的变量名,并且只在 if not frame.winfo_exists()
的情况下创建窗口——不过我不太确定这样做是否会遇到同样的问题,也就是在窗口第一次创建之前,需要给那个变量分配一个占位符。如果需要的话,这个占位符类需要有一个 winfo_exists()
方法,返回 False
。