python - Python Tkinter 在其前面显示带有 Hi 的名称
问题描述
- 您好,我已经使用 python 几个星期了,现在我开始学习 tkinter。按钮应该有文本 Say hello,当用户单击按钮时,底部标签应该显示名称,前面带有 Hi。但是我无法让标签显示“Hi {name}”。有人可以帮助我吗?
from tkinter import *
from tkinter.ttk import *
def process_name():
"""Do something with the name (in this case just print it)"""
global name_entry
print("Hi {}".format(name.get()))
def main():
"""Set up the GUI and run it"""
global name_entry
window = Tk()
name_label = Label(window, text='Enter name a name below:')
name_label.grid(row=0, column=0)
name_entry = Entry(window)
name_entry.grid(row=1, column=3)
button = Button(window, text='Say hello', command=process_name, padding=10)
button.grid(row=1, column=0, columnspan=2)
window.mainloop()
main()
- 我试过使用 set() 但它不显示。谢谢你。
解决方案
这应该可以满足您的需求。请务必阅读代码注释以了解我的操作是否正确。
虽然有几点,
- 不建议使用通配符导入,如
from tkinter import *
. 原因很简单。两者都tkinter
具有tkinter.ttk
共同的类和函数,例如Button
,Label
等等。解释器决定使用哪些变得模棱两可。 - 使用
.config()
或.configure()
更新 中的标签、按钮、条目或文本小部件tkinter
。就像我在下面的代码中所做的那样。
您的代码已修改
from tkinter import *
from tkinter.ttk import *
def process_name():
"""Do something with the name (in this case just print it)"""
global name_entry # this will print hi {name} to terminal.
print("Hi {}".format(name_entry.get()))
global nameLabel # to change'the label with hi{name} text below the button.
nameLabel.configure(text=f'Hi {name_entry.get()}')
def main():
"""Set up the GUI and run it"""
global name_entry, nameLabel
window = Tk()
name_label = Label(window, text='Enter name a name below:')
name_label.grid(row=0, column=0)
name_entry = Entry(window)
name_entry.grid(row=1, column=3)
button = Button(window, text='Say hello', command=process_name, padding=10)
button.grid(row=1, column=0, columnspan=2)
# I defined a label BELOW the button to show how to change
nameLabel = Label(window, text=' ') # an empty text Label
nameLabel.grid(row=2)
window.mainloop()
main()
推荐阅读
- java - 编写 Python Flask API 时出现 JAVA 致命错误
- node.js - 使用 Express.js 和 Mongoose 的基本 GET 请求
- python - PyQt5:如何一次连接到两个 D-Bus 服务?
- elasticsearch - elasticsearch如何决定可以并行恢复多少分片
- maven - 有没有办法在连接到存储库服务器时调试 Maven 使用正确的密码?
- php - 在保存其父模型之前“即时”创建模型
- java - 如何立即获得更大和更小的值并选择值?
- excel - VBA自动选择最后填充的单元格
- shell - 使用 shell 脚本为 UNIX 文件授予 777 权限
- python - 我想找到线程消息并使用 slack-api 将其删除