[英]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.我刚刚开始学习 python 的 tkinter,我试图让按钮在单击时更改其文本。
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.
我目前使用的代码不起作用 - 当 window 打开时,它会立即显示“点击”,作为按钮上方的 label。 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.您将
command = click()
传递给Button
构造函数。 This way, Python executes click
, then passes its return value to Button
.这样,Python执行
click
,然后将其返回值传递给Button
。 To pass the function itself, remove the parentheses - command = click
.要传递 function 本身,请删除括号 -
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.要更改现有按钮的文本(或其他选项),您可以调用其
config()
方法并将关键字 arguments 与其中的新值一起传递给它。 Note that when constructing the Button
only pass it the name of the callback function — ie don't call it).请注意,在构建
Button
时,只传递回调 function 的名称——即不要调用它)。
from tkinter import *
root = Tk()
def click():
button.config(text='clicked!')
button = Button(root, text='click me', command=click)
button.pack()
root.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.