我复制了Python代码以创建具有多个框架的Tkinter窗口。我毫无问题地将许多小部件放入其中,但是当我添加单选按钮时,尽管它们在常规窗口(没有多页)中可以正常工作,但它们的作用很有趣。无论是否设置该值,都不会选择任何单选按钮。更糟糕的是,如果我只是将鼠标指针移到单选按钮上,尽管我没有单击它,但看起来好像已被选中。如果我将鼠标指针移到两个单选按钮上,则它们看起来都被选中,这违反了单选按钮的多次选择规则。
我应该补充一点,我曾尝试过使用包管理器和网格管理器。结果是相同的。
这是我的代码的精简版:
import tkinter as tk
class MainWindow(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
# Set the title of the main window.
self.title('Multi-frame window')
# Set the size of the main window to 300x300 pixels.
self.geometry('300x100')
# This container contains all the pages.
container = tk.Frame(self)
container.grid(row=1, column=1)
self.frames = {} # These are pages to which we want to navigate.
# For each page...
for F in (StartPage, PageOne):
# ...create the page...
frame = F(container, self)
# ...store it in a frame...
self.frames[F] = frame
# ..and position the page in the container.
frame.grid(row=0, column=0, sticky='nsew')
# The first page is StartPage.
self.show_frame(StartPage)
def show_frame(self, name):
frame = self.frames[name]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text='Start Page')
label.grid(row=1, column=1)
# When the user clicks on this button, call the
# show_frame method to make PageOne appear.
button1 = tk.Button(self, text='Visit Page 1',
command=lambda : controller.show_frame(PageOne))
button1.grid(row=2, column=1)
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
# When the user clicks on this button, call the
# show_frame method to make StartPage appear.
button1 = tk.Button(self, text='Back to Start',
command=lambda : controller.show_frame(StartPage))
button1.grid(row=1, column=1)
options_label = tk.Label(self, text='Choose an option: ')
options_label.grid(row=2, column=1)
options_value = tk.IntVar()
first_option = tk.Radiobutton( self , text = 'Option 1' ,
variable = options_value , value = 1 )
second_option = tk.Radiobutton( self , text = 'Option 2' ,
variable = options_value , value = 2 )
first_option.grid(row=2, column=2)
second_option.grid(row=2, column=3)
options_value.set(1)
if __name__ == '__main__':
app = MainWindow()
app.mainloop()
问题是options_value
是一个局部值,当__init__
完成时它会被破坏。
您需要保存对它的引用,例如self.options_value
。