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

simple tkinter question – button command (display other text on click)

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()

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

>Solution :

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()
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