2013-03-22 46 views
0

我是新来的这个GUI业务与python2.7和Tkinter。我试图根据用户选择哪个Radiobutton创建一个新框架,如菜单。当我点击一个单选按钮时,它会像我想要的那样创建一个新框架,但是如果我继续单击相同的单选按钮,它将创建另一个框架和另一个框架等。似乎无法弄清楚如何检查如果Radiobutton已经标记(只点击一次)。Tkinter 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

单选按钮并不是真正为此类用途设计的。他们的目的是做出选择,而不是执行行动。我怀疑你的用户在做出选择时会感到惊讶,并弹出一个窗口。 – 2013-03-22 02:44:04

+1

好的,谢谢。只是想让程序“流畅”。我将跳过它并改为实施“提交”按钮。 – telnetmaster 2013-03-22 04:48:46

回答

0

好吧,如果你只需要一帧被同时打开,你可以在一帧上调用frame.destroy()实例化新帧之前。但是,这种方法需要在第一次选择其中一个按钮时为Tkinter初始化为destroy,否则会出现错误。为了达到我的目的,我创建了一个抛弃式类,它使用了一个不做任何事的destroy方法,然后使用该类的一个实例作为绑定到该变量的占位符,直到我的Toplevel小部件第一次创建。如果你想同时打开多个框架,只是不重复相同的选项,请尝试为每个框架使用不同的变量名称,只创建框架if not frame.winfo_exists() - 虽然我不是100%确定这不会影响到第一次创建框架之前需要分配给该变量的占位符的相同问题。如果需要,占位符类将需要一个winfo_exists()方法,将return False