pythontkinter

How do I add a variable to a method using tkinter?


I am studying python and have the following task: I want my code to display the text the user wrote when using the Button method from tkinter.

However it shows nothing, I believe the variable (text) is not working inside the method (button_clicked). It also seems I'm shadowing my variable (text), and I already tried to make it global, to no effect. Any help would be much appreciated.

from tkinter import *
window = Tk()
window.title("My first GUI program")

text="My text"

my_label = Label(text = "Hello", font= ("Arial", 24, "bold"))
my_label.pack()

#Studying Entry
input = Entry(width=10)
input.pack()
text = input.get()

#Button
def button_clicked():
   -my_label["text"] = text

button = Button(text="Click Me", command = button_clicked)
button.pack()

window.mainloop()

Solution

  • I want my code to display the text the user wrote when using the Button method from tkinter.

    Snippet:

    import tkinter as tk
    
    window = tk.Tk()
    window.title("My first GUI program")
    
    text="My text"
    
    #Button
    def button_clicked():
       txt=my_entry.get() 
       my_label.configure(text=txt)
    
    my_label = tk.Label(text = "Hello", font= ("Arial", 24, "bold"))
    my_label.pack()
    
    #Studying Entry
    my_entry = tk.Entry(width=10)
    my_entry.pack()
     
    
     
    
    button = tk.Button(text="Click Me", command = button_clicked)
    button.pack()
    
    window.mainloop()