简体   繁体   中英

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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM