Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace the text with the previous text in the label?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading