I am trying to write a code to have a label, and a button, and whenever we click on the button the defined text just replaces with the previous text in the Label. Right now it adds it the previous text.
from tkinter import *
root = Tk()
root.geometry("400x400")
my_label = Label(text="Hello").pack()
def test():
my_label = Label(text="Bye").pack()
my_button = Button(root, text="Open a file", command=test).pack()
root.mainloop()
I saw that people using config to do that. But I don’t understand what is the problem with my code.
from tkinter import *
root = Tk()
root.geometry("400x400")
global my_label
my_label = Label(text="Hello").pack()
def test():
my_label.config(text="Bye")
my_button = Button(root, text="Open a file", command=test).pack()
root.mainloop()
It gives me this error:
AttributeError: 'NoneType' object has no attribute 'config'
>Solution :
You don’t use global at the global level. You should remove that.
The PROBLEM is that the .pack() method returns None. Tkinter is a hopelessly antiquated relic of software days gone by, and does not use good object practices. You need
my_label = Label(text="hello")
my_label.pack()