'How to replace the text with the previous text in the label? [duplicate]

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 1:[1]

The problem with your tkinter code is covered in the accepted answer to the question Tkinter: AttributeError: NoneType object has no attribute .

As for what you want to know how to do:

While, generally speaking, you can change the options of an existing widget by using the universal widget config() method, as you're doing. There's an even better way to do things when you want to change a value that one (or more) of them is displaying. In those cases you can refer one or more widgets to a tkinter Variable and then just update the variable's value and all the widgets referring to it change.

Here's how to do things that way.

import tkinter as tk  # PEP 8 recommends against `import *`.


root = tk.Tk()
root.geometry("400x400")

label_text = tk.StringVar(value="Hello")

my_label = tk.Label(textvariable=label_text)
my_label.pack()

def test():
    label_text.set("Bye")

my_button = tk.Button(root, text="Open a file", command=test)
my_button.pack()

root.mainloop()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 martineau