0

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'
martineau
  • 119,623
  • 25
  • 170
  • 301
pymn
  • 171
  • 2
  • 10

2 Answers2

1

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()
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
0

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()
martineau
  • 119,623
  • 25
  • 170
  • 301