tkinter checkbutton从其他文件导入类时未显示正确的值

2024-10-02 20:31:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个主程序,它可以做一些很酷的东西,我目前正在设置一个“设置编辑器”,让用户更改一些与GUI相关的东西和默认值。它从正确读入的文本文件中读取值,并将其保存到字典self.propertiesDict中。有些选项是开/关开关,所以我使用复选按钮。让我困惑的是以下行为:当我直接执行setingseditor.py(创建设置窗口的脚本)时,代码工作得非常好。所有复选按钮都设置为active/True。然而,当我在我的主程序中包含我的settingsEditor并调用它时,它会创建fine,但所有的复选按钮都显示错误的值:False。为了找到答案,我阅读了很多主题,但我认为我避免了最常见的错误:

  • 我使用tk变量
  • tk变量在按钮之前创建和设置
  • 变量不仅在局部范围内(前缀为self)

如您所见,我尝试使用IntVar和BooleanVar,但两者都不能正常工作。还有一点很奇怪,当我使用ttk.checkbuttons时,我得到了描述的问题here。我使用VisualStudio进行调试,在逐行调试的过程中,我看不到任何差异,除了错误的显示结果。我很乐意接受任何建议。很抱歉没有提供完整的MWE,如果这里没有人可以帮助我,我会这样做

设置编辑器.py

import tkinter as tk
from tkinter import ttk
...
class mySettingsEditor:
    def __init__(self):
        ...
    def createGUI(self):
        # Show main options on startup on/off
        self.showOptionsVar = tk.IntVar()
        self.showOptionsVar.set(str2int(self.propertiesDict['showMainOptionsExpanded']))
        print(self.showOptionsVar.get())
        self.checkBtn1 = tk.Checkbutton(Frame, text='Main Options Section', variable=self.showOptionsVar)
        self.checkBtn1.grid(column=0,row=2)

        # Show main STL section on startup on/off
        self.showMainSTLVar = tk.BooleanVar()
        self.showMainSTLVar.set(str2bool(self.propertiesDict['showMainSTLSectionExpanded']))
        print(self.showMainSTLVar.get())
        self.checkBtn2 = tk.Checkbutton(Frame, text='Main STL Section', variable=self.showMainSTLVar)
        self.checkBtn2.grid(column=0,row=3)

main.py

from settingsEditor import mySettingsEditor
...
settEditor = mySettingsEditor()

这是单独执行时在GUI中的外观(左侧为打印输出的终端):

Works fine!

这是我在main.py中添加它时的结果。这些框是未选中的,但是.get()告诉我这些值已正确分配给tk变量

Ehm, well, no.


Tags: pyimportselfgetmainon错误编辑器