python - 每次在`tkinter`中按下按钮时,如何获得不同的标签值?
问题描述
所以我正在制作一个随机名称生成器。一切都在我的 GUI 中完成了。问题是我只能按一次生成按钮来获取所有需要的值。如何无限次按下按钮,每次按下按钮时获得不同的值。
我需要做某种循环吗?我lambda
在里面放了一个。这会阻止值在您打开 GUI 后立即显示在我的屏幕上。这样您就可以按下按钮,文本就会正常显示。
firstnameli = ['Chris ', 'Kevin ', 'Jeff ', 'Marty ', 'Dolen ']
lastnameli = ['Smith', 'Miller', 'Jones', 'Davis', 'Brown']
full_name = random.choice(firstnameli) + random.choice(lastnameli)
#this allows text to be put in the text box
estr = StringVar()
estr.set(full_name)
fullnameentry = Entry(MyWin, borderwidth=5, font=("Helvetica", 15))
def buttonfunc():
fullnameentry.config(text=estr)
genbutton = Button(MyWin, text="GENERATE", activebackground="blue", command= lambda: buttonfunc())
解决方案
您只生成一次随机名称。从那时起,estr
始终是相同的值。
如果你觉得舒服,lambda
你可以用它来制作full_name
一个函数:
full_name = lambda: random.choice(firstnameli) + random.choice(lastnameli)
之后,您将不得不调用 full_name
它,因为它不再是一个简单的字符串变量,而是一个函数:
estr.set(full_name())
此外,您似乎错过textvariable=estr
了fullnameentry
.
一切都放在一起:
firstnameli = ['Chris ', 'Kevin ', 'Jeff ', 'Marty ', 'Dolen ']
lastnameli = ['Smith', 'Miller', 'Jones', 'Davis', 'Brown']
full_name = lambda: random.choice(firstnameli) + random.choice(lastnameli)
#this allows text to be put in the text box
estr = StringVar()
estr.set(full_name())
fullnameentry = Entry(MyWin, textvariable=estr, borderwidth=5, font=("Helvetica", 15))
def buttonfunc():
estr.set(full_name())
genbutton = Button(MyWin, text="GENERATE", activebackground="blue", command=buttonfunc)
我还认为您的代码在某些时候可能有点过于复杂。这是一个最小且完整的tkinter
示例,也许这会在某种程度上对您有所帮助:
import tkinter as tk
import random
def random_name():
first_names = ['Chris', 'Kevin', 'Jeff', 'Marty', 'Dolen']
last_names = ['Smith', 'Miller', 'Jones', 'Davis', 'Brown']
full_name = '{} {}'.format(random.choice(first_names), random.choice(last_names))
return full_name
def update_label_and_entry():
new_random_name = random_name()
label.config(text=new_random_name)
entry.delete(0, tk.END) # delete content from 0 to end
entry.insert(0, new_random_name) # insert new_random_name at position 0
root = tk.Tk()
label = tk.Label(root)
label.pack()
entry = tk.Entry(root)
entry.pack()
button = tk.Button(root, text="New random name", command=update_label_and_entry)
button.pack()
root.mainloop()
当然,这段代码并不完美。代码可以进一步改进,例如通过移动first_names
和last_names
到全局命名空间,因此其他方法也可以访问这些值。此外,您可以为您的窗口或包含该update_label
方法的标签编写一个类。
推荐阅读
- c - 指向结构指针的内存分配
- spring - Spring集成sftp问题
- javascript - Nodejs、Express 和 WebSockets:将消息中继到发送者以外的所有客户端
- ios - ARKit:将多个物体放置在室外时,虚拟物体固定在相机框架上
- asterisk - 将 sip 呼叫转接到号码
- vue.js - 如何使用 VueX 存储多个 api 的数据并将属性添加到响应中
- mysql - 在 ASP.NET Core 中连接到 MySql 数据库
- javascript - 悬停在另一个 div 上时显示和隐藏按钮
- eclipse - 为什么 Eclipse 有两个“Referenced Libraries”文件夹,“Referenced Libraries”文件夹与“Web App Libraries”文件夹有何不同?
- php - Laravel 邮件外观:如何单独发送给收件人数组?