我对python2.7和Tkinter的GUI业务还不熟悉。我试图根据用户选择的单选按钮创建一个新的框架,比如菜单。当我点击一个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...
如果一次只需要打开一个框架,那么可以在实例化新框架之前对前一个框架调用
frame.destroy()
。但是,这种方法要求在第一次选择其中一个按钮时,Tkinter必须初始化为destroy
,否则您将得到一个错误。出于我的目的,我只是创建了一个带有destroy
方法的一次性类,然后使用该类的一个实例作为绑定到该变量的占位符,直到我的顶层小部件第一次被创建。如果您希望同时打开多个框架,只是不重复同一选项,请尝试为每个帧使用不同的变量名,并且只创建帧if not frame.winfo_exists()
,尽管我不能百分之百地确定在第一次创建帧之前,这不会受到同样的问题的影响,即需要为该变量分配占位符。如果需要这样的话,占位符类将需要一个winfo_exists()
方法,该方法将return False
。在相关问题 更多 >
编程相关推荐