JimmyCarlos
JimmyCarlos

Reputation: 1952

Python: How to use a tkinter Checkbutton in OOP functions

I have got stuck with this particular bit of code. I have condensed down the problem to this section.

I am running a sort of menu in Python, where the first menu sends you to the second menu, and in the second menu, there is a checkbutton the user can toggle on/off. In the third menu, I want it to read if the checkbutton is on/off and convert it to a Boolean. Code:

import tkinter as tk

class MainMenu(object):
    def __init__(self):
        self.launch_MainMenu()
    def launch_MainMenu(self):
        self.master = tk.Tk()
        tk.Button(self.master,text="MY BUTTON",command= lambda:self.launch_SideMenu()).grid()
        tk.mainloop()
    def launch_SideMenu(self):
        self.master2 = tk.Tk()
        self.var1 = tk.IntVar()
        tk.Checkbutton(self.master2,variable=self.var1).grid()
        tk.Button(self.master2,text="Test",command= lambda:self.launch_FinalMenu()).grid()
    def launch_FinalMenu(self):
        d = bool(int(self.var1.get()))
        print(d,self.var1.get())

mainMenu = MainMenu()

Output: Whether the checkbox is on or off, it outputs "False 0".

Any help would be very much appreciated!

Upvotes: 0

Views: 51

Answers (1)

JimmyCarlos
JimmyCarlos

Reputation: 1952

As per the hint from Lafexlos, the error is in calling tk.Tk() twice. For a new window, you must use tk.Toplevel().

Simply changing the keyline to:

self.master2 = tk.Toplevel()

fixes everything. This took me a long time to work out. Thanks for the help, and best of luck to you coders reading this in the future.

Upvotes: 3

Related Questions