lundi 20 septembre 2021

Erratic Behavior of Tkinter Checkboxes

This is the code for a window with an entry field and 2 checkboxes:

Snippet 1:

    root = Tk()
    root.title('Window 1')

    def var_states():
        for item in field_list:
        print(item.get())

    field_list = []

    entry_field = ttk.Entry(root)
    entry_field.grid()
    field_list.append(entry_field)

    var1 = IntVar()
    cb01 = ttk.Checkbutton(root, text='A', variable=var1)
    cb01.grid()
    field_list.append(var1)

    var2 = IntVar()
    cb02 = ttk.Checkbutton(root, text='B', variable=var2)
    cb02.grid()
    field_list.append(var2)

    button = ttk.Button(root, text='Show', command=var_states)
    button.grid()

    root.mainloop()

I type "hello" into the entry field, check box "B", and click "Show." The output in the console is:
hello
0
1

So far, so good. This works as expected.

Now, this is the code for a window with a button which opens another window by calling a function:

Snippet 2:

from tkinter import *
from tkinter import ttk
from window2 import window2_func

root = Tk()
root.title('Window 1')

button = ttk.Button(root, text='Open Window 2', command=window2_func)
button.grid()

root.mainloop()

This is the code for the second window. The code for the second window is within a function because I don't know how to do it differently:

Snippet 3:

from tkinter import *
from tkinter import ttk

def window2_func():
    root = Tk()
    root.title('Window 2')
    def var_states():
        for item in field_list:
            print(item.get())

    field_list = []

    entry_field = ttk.Entry(root)
    entry_field.grid()
    field_list.append(entry_field)

    var1 = IntVar()
    cb01 = ttk.Checkbutton(root, text='A', variable=var1)
    cb01.grid()
    field_list.append(var1)

    var2 = IntVar()
    cb02 = ttk.Checkbutton(root, text='B', variable=var2)
    cb02.grid()
    field_list.append(var2)

    button = ttk.Button(root, text='Show', command=var_states)
    button.grid()

    root.mainloop()

I start the first script, click the 'Open Window 2' button, and Window 2 appears. However, in there the checkboxes don't work. I type 'hello' into the entry field, manipulate the checkboxes, and click the 'Show'-button. Only the value of the entry field appears accurately in the console. No matter what I do to the checkboxes, their value remains 0--they also appear to have 3 states now: empty, filled black, checked.

It seems that checkboxes don't work, if one calls a new window through a button command that triggers a function. (I have tried creating a window with buttons within a function that runs upon running the script and they work fine. So, that the window is within a function doesn't seem to be the problem.)

My question, most importantly: how do I get the checkboxes in Snippet 3 to work?

And out of curiosity: why the difference in behavior Snippet 1 <--> Snippet 2 + 3




Aucun commentaire:

Enregistrer un commentaire