在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()

提前谢谢!

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

实现这一点的方法是首先创建并清空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()

最新更新