python - 为什么单选按钮不能在具有多个帧的 Tkinter 窗口中工作?
问题描述
我复制了 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
.
推荐阅读
- python - 无法安装pyodbc,缺少头文件,命令提示符:致命错误C1083:无法打开包含文件:'windows.h':没有这样的文件或目录
- java - 未处理的异常:PlatformException (sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null, null) - 在一个系统中运行良好
- php - footer-home.inc.php 不在远程服务器上显示,而仅在本地主机上显示
- javascript - 嵌套的反应组件没有渲染被卡住了几个小时
- python - 如何从我的 __init__.py 修改其他文件中的变量?
- python - 对所有视图应用 django 身份验证
- git - Git 分支工作流
- java - Maven获取依赖的相对路径
- machine-learning - 使用 ML 查找相似项目
- google-chrome - Chrome DevTools 在左或右停靠时的默认宽度是多少?