Python,Tkinter,如何基于buttonclick更改GUI

发布于 2024-12-04 15:47:58 字数 401 浏览 0 评论 0原文

我在编程作业中使用 Tkinter 并遇到以下问题。 我希望用户在文本框中输入值,并且当他/她单击提交按钮时,我想根据在文本框中输入的数字在 GUI 上添加其他字段。

我尝试将代码放在函数“displayText()”中,按下提交按钮时会调用该函数;但是,我放置在其中的 GUI 相关代码是在加载窗口时加载的。

import tkinter

#When user clicks on button
def displayText():
    #DO CHANGE IN GUI

root = tkinter.Tk()
button = tkinter.Button(root, text="Submit", command=displayText())
button.pack()

root.mainloop()

I am using Tkinter in a programming assignment and have the following problem.
I want the user to enter the value in a textbox, and I want to add additional fields on the GUI based on the number entered in the textbox when he/she clicks the submit-button.

I tried to place code inside of the function 'displayText()', which is called when the submit-button is pressed; however, the GUI-related code that I placed inside of it was loaded when the window was loaded.

import tkinter

#When user clicks on button
def displayText():
    #DO CHANGE IN GUI

root = tkinter.Tk()
button = tkinter.Button(root, text="Submit", command=displayText())
button.pack()

root.mainloop()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

人间☆小暴躁 2024-12-11 15:47:58

问题出在这行代码中:

button = tkinter.Button(root, text="Submit", command=displayText())

command 选项采用命令的引用。相反,您所做的是调用命令 (displayText()) 并将该命令的结果提供给选项。您需要删除 () 以便实际运行的命令与该选项相关联,如下所示:

button = tkinter.Button(root, text="Submit", command=displayText)

The problem is in this line of code:

button = tkinter.Button(root, text="Submit", command=displayText())

The command option takes a reference to a command. What you are doing instead is calling a command (displayText()) and giving the results of that command to the option. You need to remove the () so that the actual command to run is associated with the option, like so:

button = tkinter.Button(root, text="Submit", command=displayText)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文