Search code examples
pythontkintertkinter-entrytkinter.checkbutton

I want to get value of Entrybox and Checkbutton but I get nothing why? (I am new to tkinter)


I want to get value of Entrybox and Checkbutton but I get nothing why? (I am new to tkinter)

from tkinter import *
 
def m1():
    m1 = Tk()
    entry_val = StringVar()
    check_val = IntVar()
    Entry(m1, textvariable=entry_val).pack()
    Checkbutton(m1, text='CheckButton', variable=check_val).pack()

    def show():
        print(entry_val.get())
        print(check_val.get())

    Button(m1, text='click!', command=show).pack()
    m1.mainloop()


def main():
    main = Tk()

    Button(main, text='click! (main)', command=m1).pack()
    main.mainloop()


main()

Solution

  • The short and simple answer:

    In your code you need to change m1 = Tk() to m1 = Toplevel(). This will fix your issue.

    The long answer:

    When writing a Tkinter GUI 99.99% of the time you are only ever going to use 1 tkinter instance Tk(). The reason for this is that each instance of Tk() is contained within its own personal "Sandbox". Meaning it cannot play with others. So one instance of Tk() cannot communicate with a separate Tk() instance.

    It is my understanding that if you do not specify what instance a method belongs to within the method then it will default to the 1st instance of Tk(). So the StringVar() and IntVar() you have create cannot be printed due to them belonging to main. Because main cannot talk to m1 you cannot update this value.

    We can actually test this if you change:

    entry_val = StringVar()
    check_val = IntVar()
    

    To:

    entry_val = StringVar(m1)
    check_val = IntVar(m1)
    

    You will see your variables update properly.

    Or if you change m1 = Tk() to m1 = Toplevel() (the correct solution) you will see that everything works as needed.

    Toplevel() is specifically designed for creating new windows in tkinter so everything can stay in the same "Sandbox" and work together.