Search code examples
pythontkintertkinter.checkbutton

tkinter checkbutton not displaying correct value when class imported from other file


I have a main program which does some cool stuff and I am currently setting up a 'settings editor' to let the user change some GUI related stuff and default values. It reads values from a text file, which is read in correctly and saves them to a dictionary self.propertiesDict. Some of the options are on/off switches, so I use checkbuttons for them. What is puzzling me is following behavior: the code works perfectly fine, when I execute the settingsEditor.py (the script creating the settings window) directly. All the checkbuttons are set to active / True. However, when I include my settingsEditor in my main program and call it, it creates fine but all the checkbuttons show the wrong value: False. I read a lot of topics here to find an answer, but I think I avoided the most common errors:

  • I use the tk variables
  • tk variables are created and set prior to the buttons
  • variables are not only in local scope (prefixed self.)

As you can see, I tried with an IntVar and a BooleanVar, but neither is working correctly. Something else is strange, when I use ttk.checkbuttons, I get the issue described here. I use Visual Studio for debugging and I can't see any difference in the process when going trough line by line, except for the wrong display result. I am happy for any suggestion. Sorry for not providing a full MWE, I will do, if nobody can help me from this here.

settingsEditor.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()

This is how it looks in the GUI when executed separately (terminal with print output to the left):

Works fine!

Thats the result when I add it in main.py. The boxes are unchecked, but .get() tells me the values are correctly assigned to the tk variables.

Ehm, well, no.


Solution

  • As suggested by jasonharper, switching to Toplevel() for the child windows fixed the issue. Thanks alot!