首页 > 解决方案 > 为什么在单击按钮之前执行该功能?

问题描述

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

这里应该在单击按钮时显示文本,但在此之前执行该函数,并且在我运行代码时显示文本。

标签: pythontkinter

解决方案


 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


推荐阅读