1

i've just started learning tkinter for python, and i'm trying to get the button to change its text when it's clicked on.

this seems like a very simple question, but i can't find any answers. the code i'm using at the moment doesn't work - when the window opens, it displays 'clicked!' as a label above the button immediately, before i've clicked on the button.

from tkinter import *

root = Tk()

def click():
    label = Label(root, text = 'clicked!')
    label.pack()

button = Button(root, text='click me', command = click())

button.pack()

root.mainloop()

2 Answers 2

1

To change an existing button's text (or some other option), you can call its config() method and pass it keyword arguments with new values in them. Note that when constructing the Button only pass it the name of the callback function — i.e. don't call it).

from tkinter import *

root = Tk()

def click():
    button.config(text='clicked!')

button = Button(root, text='click me', command=click)
button.pack()

root.mainloop()
Sign up to request clarification or add additional context in comments.

Comments

0

You're passing command = click() to the Button constructor. This way, Python executes click, then passes its return value to Button. To pass the function itself, remove the parentheses - command = click.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.