Home > Mobile >  Python and tkinter: Global variable not working?
Python and tkinter: Global variable not working?

Time:03-06

This is a simple program using tkinter. It's basically supposed to display whatever the user types in the inp field and display it as a label on clicking a button. Here I have tried containing the tkinter value as a global variable and then using it in change_label():

from tkinter import *


def change_label():
    global new_text
    my_label['text'] = new_text


window = Tk()
window.title("My first GUI program")
window.minsize(width=500, height=300)

my_label = Label(text="This is a label.", font=('Arial', 24, 'bold'))
my_label.pack()

button = Button(text="Click me!", command=change_label)
button.pack()

inp = Entry(width=10)
inp.pack()
new_text = inp.get()

window.mainloop()

But on running, clicking the button results in showing an empty label.

However, if I declare new_text inside change_label(), the code works fine.

from tkinter import *


def change_label():
    new_text = inp.get()
    my_label['text'] = new_text


window = Tk()
window.title("My first GUI program")
window.minsize(width=500, height=300)

my_label = Label(text="This is a label.", font=('Arial', 24, 'bold'))
my_label.pack()

button = Button(text="Click me!", command=change_label)
button.pack()

inp = Entry(width=10)
inp.pack()

window.mainloop()

Why does the first code not work while the second does?

CodePudding user response:

first off you should never declare a global var inside a function that wont be global until its called at least once

from tkinter import *

global new_text
def change_label():
    my_label['text'] = new_text


window = Tk()
window.title("My first GUI program")
window.minsize(width=500, height=300)

my_label = Label(text="This is a label.", font=('Arial', 24, 'bold'))
my_label.pack()

button = Button(text="Click me!", command=change_label)
button.pack()

inp = Entry(width=10)
inp.pack()
new_text = inp.get()

window.mainloop()

CodePudding user response:

first off you should never declare a global var inside a function that wont be global until its called at least once

from tkinter import *

global new_text

def change_label():
    new_text = inp.get()
    print(new_text)
    my_label['text'] = new_text


window = Tk()
window.title("My first GUI program")
window.minsize(width=500, height=300)

my_label = Label(text="This is a label.", font=('Arial', 24, 'bold'))
my_label.pack()

button = Button(text="Click me!", command=change_label)
button.pack()

inp = Entry(width=10)
inp.pack()


window.mainloop()
  • Related