python - 为什么在单击按钮之前执行该功能?
问题描述
刚从 tkinter 开始并正在检查按钮,就出现了这个问题。
import tkinter as tk
def showtext(text):
txt = tk.Text(gui)
txt.insert(tk.END, text)
txt.pack()
gui = tk.Tk()
btn = tk.Button(gui, text="this is a button", fg="white", bg="black",
activebackground="red", activeforeground="purple", command=showtext("this worked"))
btn.place(x=280, y=230)
gui.title('GUI')
gui.geometry("700x500+50+50")
gui.mainloop()
这里应该在单击按钮时显示文本,但在此之前执行该函数,并且在我运行代码时显示文本。
解决方案
btn = tk.Button(gui, text="this is a button", fg="white", bg="black",
activebackground="red", activeforeground="purple", command=showtext("this worked"))
这样做的意思是:做showtext("this worked")
和使用返回值作为command
,你可能意味着函数不是command
它的返回值,所以你应该这样做command=showtext
。
推荐阅读
- phonegap-plugins - Phonegap 显示错误 - “哦,天哪。你的构建失败了。”
- scala - Scala 在 \n 上拆分
- javascript - “$.get 不是函数”使用来自 babel-node 的 jQuery
- go - Go 自定义错误类型:为什么要返回指向错误的指针?
- javascript - Vanilla JavaScript 向元素添加类
- javascript - 如何设置 cookie 的多个值并将它们全部显示在另一个页面上?
- python - Python RAW 套接字解释数据字节
- c - C 中的堆栈代码在运行后立即崩溃并停止工作
- azure - 来自 kubernetes pod 的 Squid 代理连接
- machine-learning - 为什么 Keras Early Stopping 功能不会停止训练,虽然监测值在增加?