Selfiatus1
Selfiatus1

Reputation: 11

Uncheck boxes when another is checked

So the problem is with the if function, it just won’t work. It totally ignores all value changes and does not change any value at all. What is wrong with this code?

import tkinter as tk
root = tk.Tk()

CheckVar4 = tk.IntVar()
CheckVar5 = tk.IntVar()

C4 = tk.Checkbutton(root, text = "Medium terms", variable = CheckVar4, \
                 onvalue = 1, offvalue = 0, height=1, \
                 width = 12)

C5 = tk.Checkbutton(root, text = "Hard terms", variable = CheckVar5, \
                 onvalue = 1, offvalue = 0, height=1, \
                 width = 8)

if CheckVar4.get() == 1:
    CheckVar5.set(0)

if CheckVar5.get() == 1:
    CheckVar4.set(0)

root.mainloop()

Upvotes: 0

Views: 2355

Answers (3)

toyota Supra
toyota Supra

Reputation: 4545

Typo error line 16 and 18. Missing widgets pack()

if CheckVar4.get() == 1:
    CheckVar4.set()

if CheckVar5.get() == 1:
    CheckVar5.set(0)

C4.pack(padx=0)
C5.pack(padx=0)

Upvotes: 0

Silvio Duarte
Silvio Duarte

Reputation: 41

Try this:

C4 = tk.Checkbutton(root, text = "Medium terms", variable = CheckVar4, \
                 onvalue = 1, offvalue = 0, height=1, \
                 width = 12, command=lambda:CheckVar5.set(0))

C5 = tk.Checkbutton(root, text = "Hard terms", variable = CheckVar5, \
                 onvalue = 1, offvalue = 0, height=1, \
                 width = 8, command=lambda:CheckVar4.set(0))

Upvotes: 0

AdityaB
AdityaB

Reputation: 133

Maybe want to use radio buttons instead? Example bellow from here:

import tkinter as tk

root = tk.Tk()

v = tk.IntVar()

tk.Label(root, 
        text="""Choose a 
programming language:""",
        justify = tk.LEFT,
        padx = 20).pack()
tk.Radiobutton(root, 
              text="Python",
              padx = 20, 
              variable=v, 
              value=1).pack(anchor=tk.W)
tk.Radiobutton(root, 
              text="Perl",
              padx = 20, 
              variable=v, 
              value=2).pack(anchor=tk.W)

root.mainloop()

Upvotes: 1

Related Questions