首页 > 解决方案 > 每次在`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())

标签: pythonbuttontkintercommand

解决方案


您只生成一次随机名称。从那时起,estr始终是相同的值。

如果你觉得舒服,lambda你可以用它来制作full_name一个函数:

full_name = lambda: random.choice(firstnameli) + random.choice(lastnameli)

之后,您将不得不调用 full_name它,因为它不再是一个简单的字符串变量,而是一个函数:

estr.set(full_name())

此外,您似乎错过textvariable=estrfullnameentry.

一切都放在一起:

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_nameslast_names到全局命名空间,因此其他方法也可以访问这些值。此外,您可以为您的窗口或包含该update_label方法的标签编写一个类。


推荐阅读