0

我是 python2.7 和 Tkinter 的 GUI 业务新手。我正在尝试根据用户选择的 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...
4

1 回答 1

0

好吧,如果您一次只需要打开一个帧,您可以frame.destroy()在实例化新帧之前调用前一帧。但是,这种方法需要destroy在第一次选择一个按钮时为 Tkinter 初始化一些东西,否则你会得到一个错误。出于我的目的,我只是用一个destroy什么都不做的方法创建了一个一次性类,然后使用该类的一个实例作为绑定到该变量的占位符,直到第一次创建我的 Toplevel 小部件。如果您希望同时打开多个框架,而不是相同选项的重复项,请尝试为每个框架使用不同的变量名称并仅创建框架if not frame.winfo_exists()--尽管我不是 100% 确定这不会受到同样的问题的影响,即在第一次创建框架之前需要分配给该变量的占位符。如果需要,占位符类将需要一个winfo_exists()方法,该方法将return False.

于 2015-05-16T21:35:20.360 回答