首页 > 解决方案 > 在 tkinter 标签小部件中显示函数的输出

问题描述

我最近一直在阅读大量的堆栈溢出,我要感谢所有活跃在这里的人的贡献。这个社区在我学习 python 方面帮助了我很多!

我正在尝试编写一个非常简单的名称生成器程序,每次在 tkinter GUI 中按下按钮时,都会在标签小部件中生成一个新名称。

生成器使用随机模块从预编译列表中挑选单词并将它们组合在一起,其结构在函数“generate_name”中定义。

我已经让程序在控制台中正常工作,但我不知道如何让它与 tkinter 一起工作。

我希望构建一个 tkinter GUI,您可以在其中按下按钮,“generate_name”的输出将显示在 tkinter 标签上。但是,我似乎无法实现这一点,只能获得要在控制台中显示的函数的输出。

我已经阅读了许多与类似问题相关的帖子,但我似乎无法理解这一点。我已经尝试了许多替代方法,虽然我已经能够显示更简单函数的输出,例如,你用变量做简单的数学方程,但我根本无法让随机生成的名称出现除了控制台之外的任何地方。

希望我能够清楚地表达我的问题。

这是我正在处理的代码的简化版本:

from tkinter import *
import random

#Lists of words that will be used by the generate_name() function

wordclass1 = (
'word1',
'word2',
'word3',
)

wordclass2 = (
'word4',
'word5',
'word6',
)

wordclass3 = (
'word7',
'word8',
'word9',
)

#These functions do the actual random generation of the names.

def name1():
    full_name = random.choice(wordclass1) + " " + random.choice(wordclass2)
    print(full_name)

def name2():
    full_name = random.choice(wordclass2) + " " + random.choice(wordclass3)
    print(full_name)

def name3():
    full_name = random.choice(wordclass1) + " " + random.choice(wordclass2) + " " + random.choice(wordclass3)
    print(full_name)

#This function randomly picks the individual name that should be displayed on the tkinter label

def generate_name():
    list = (name1, name2, name3)
    return(random.choice(list)())
    name = random.choice(list)

#This function is supposed to display the text on the tkinter label

def write():
    label = Label(root, text=(generate_name()))
    label.pack()

root = Tk()

button = Button(root, text="Generate a name!", command=write)
button.pack()

root.mainloop()

先感谢您!

我仍然是一个初学者,我确信我的代码有很多问题,但任何建议都将不胜感激!

标签: pythontkinter

解决方案


这样做的方法是首先创建并清空Label,然后在单击 时将新内容放入其中Button(使用名为 的通用小部件方法config())。我还更改了您的其他一些功能的工作方式,特别是generate_name()为了让一切正常工作——我认为大多数更改都是显而易见的。

from tkinter import *
import random

#Lists of words that will be used by the generate_name() function

wordclass1 = (
'word1',
'word2',
'word3',
)

wordclass2 = (
'word4',
'word5',
'word6',
)

wordclass3 = (
'word7',
'word8',
'word9',
)

#These functions do the actual random generation of the names.

def name1():
    full_name = random.choice(wordclass1) + " " + random.choice(wordclass2)
    return full_name

def name2():
    full_name = random.choice(wordclass2) + " " + random.choice(wordclass3)
    return full_name

def name3():
    full_name = random.choice(wordclass1) + " " + random.choice(wordclass2) + " " + random.choice(wordclass3)
    return full_name

#This function randomly picks the individual name that should be displayed on the tkinter label

def generate_name():
    return random.choice([name1, name2, name3])()

#This function is supposed to display the text on the tkinter label

def write():
    label.config(text=generate_name())

root = Tk()

label = Label(root, text='')
label.pack()
button = Button(root, text="Generate a name!", command=write)
button.pack()

root.mainloop()


推荐阅读