首页 > 解决方案 > 我没有在 python 中获得所需的输出

问题描述

from tkinter import *

root = Tk()
root.title('printer')
label = Label(root, text = "WELCOME", fg = "grey")

label.pack()
textbox = Entry(root)
textbox.pack()


def whenclicked():
    global hello
    hello = "textbox.get()"
    label1 = Label(root, text = hello)
    label1.pack()



button = Button(root, text = "print it", command = whenclicked())
button.pack()
root.mainloop()

当我运行此代码时,在我单击按钮之前,输出已经存在。这有什么问题?

标签: pythonbuttontkinter

解决方案


函数的所有参数都在函数调用之前进行评估,因此当您调用时:

Button(root, text = "print it", command=whenclicked())

它首先调用whenclicked()然后将其结果传递给Button构造函数。command参数应该是一个函数,所以像这样传递它:

Button(root, text = "print it", command=whenclicked)

hello = "textbox.get()"(不相关,但如果要获取文本框内容,引号是多余的。)


推荐阅读