[英]Why aren't radiobuttons working in a Tkinter window with multiple frames?
我复制了 Python 代码以创建具有多个帧的 Tkinter window。 我毫无问题地将多种小部件放入其中,但是当我添加单选按钮时,它们的行为很有趣,尽管它们在常规 window(没有多个页面)中工作正常。 无论我是否设置值,都不会选择任何单选按钮。 更糟糕的是,如果我只是将鼠标指针移到单选按钮上,它看起来会被选中,尽管我没有单击它。 如果我将鼠标指针放在两个单选按钮上,它们看起来都被选中,违反了单选按钮的多选规则之一。
我应该补充一点,我使用包管理器和网格管理器进行了尝试。 结果是一样的。
这是我的代码的精简版本:
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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.