Home > Software engineering >  tkinter,Checkbutton, the same code has different result in def or single file
tkinter,Checkbutton, the same code has different result in def or single file

Time:10-12

I have very strange issue.

I write on code for Checkbutton (tkinter).

  1. if the code in one single file, it can work. The button "check" can show the current status (the value change)

Debug -- in check proc

The value of C1 is : 1

The value of C2 is : 0

Debug -- in check proc The value of C1 is : 1

The value of C2 is : 1

2 if the code in one def, the value always are 0 (not change)

How can I fix this issue?

Thanks

The single file:

#!/usr/bin/python3

from tkinter import *


root = Tk()


CheckVar1 = IntVar()
CheckVar2 = IntVar()
Name1 =  "Music"
Name2 =  "Video"

C1 = Checkbutton(root, text = Name1, variable = CheckVar1, onvalue = 1,  offvalue = 0 )
C2 = Checkbutton(root, text = Name2, variable = CheckVar2,onvalue = 1, offvalue = 0 )

C1.pack()
C2.pack()

def check_value():
    print("Debug -- in check proc")
    print("The value of C1 is :", CheckVar1.get())
    print("The value of C2 is :", CheckVar2.get())


Button(root, text = 'check', command = check_value).pack()

mainloop()

The file with def

#!/usr/bin/python3

from tkinter import *

def tree_ts_summary():
    root = Tk()
    
    
    CheckVar1 = IntVar()
    CheckVar2 = IntVar()
    Name1 =  "Music"
    Name2 =  "Video"
    
    C1 = Checkbutton(root, text = Name1, variable = CheckVar1, onvalue = 1,  offvalue = 0 )
    C2 = Checkbutton(root, text = Name2, variable = CheckVar2,onvalue = 1, offvalue = 0 )
    
    C1.pack()
    C2.pack()
    
    def check_value():
        print("Debug -- in check proc")
        print("The value of C1 is :", CheckVar1.get())
        print("The value of C2 is :", CheckVar2.get())
    
    
    Button(root, text = 'check', command = check_value).pack()
    
    mainloop()


root_top = Tk()

Button(root_top, text = 'call_def', command = tree_ts_summary).pack()

mainloop()


CodePudding user response:

As mentioned by @acw1668 in the comments you shouldn't have multiple instances of Tk(). You can change your code like this:

from tkinter import *

def tree_ts_summary():

    
    
    CheckVar1 = IntVar()
    CheckVar2 = IntVar()
    Name1 =  "Music"
    Name2 =  "Video"
    
    C1 = Checkbutton(root, text = Name1, variable = CheckVar1, onvalue = 1,  offvalue = 0 )
    C2 = Checkbutton(root, text = Name2, variable = CheckVar2,onvalue = 1, offvalue = 0 )
    
    C1.pack()
    C2.pack()
    
    def check_value():
        print("Debug -- in check proc")
        print("The value of C1 is :", CheckVar1.get())
        print("The value of C2 is :", CheckVar2.get())
    
    
    Button(root, text = 'check', command = check_value).pack()
    


root = Tk()

Button(root, text = 'call_def', command = tree_ts_summary).pack()
root.mainloop()
  • Related