使随机生成的单词出现的按钮.Python Tkinter



非常基本的东西。我有这个代码:

from tkinter import *
import secrets
def stuff():
stuff = ["study math",
"Phone", "social",
"study python","tv",
"exercise"]
print(secrets.choice(stuff))
window = Tk()
button = Button(window,
text="click me",
command=stuff,
font=("Comic Sans", 40),
fg="#00FF00",
bg="black",
activeforeground="#00FF00",
activebackground="black")
button.grid()

但这只会在终端上打印列出的单词。我想把这个单词作为标签打印在GUI上。我正在尝试这样的东西,

def stuff():
stuff = ["study math",
"Phone", "social",
"study python","tv",
"exercise"]
Label(window, secrets.choice(stuff)).grid(row=1)

对接。。不太明白。有人能给我指正确的方向吗?

您需要使用text选项来设置Label小部件的文本。还建议在stuff()函数外创建一次标签。

from tkinter import *
import secrets
def stuff():
stuff = ["study math",
"Phone", "social",
"study python","tv",
"exercise"]
# update the label with the random choice
choice.config(text=secrets.choice(stuff))

window = Tk()
button = Button(window,
text="click me",
command=stuff,
font=("Comic Sans", 40),
fg="#00FF00",
bg="black",
activeforeground="#00FF00",
activebackground="black")
button.grid(row=0, column=0) # better to specify row and column
# label to show the random message
choice = Label(window)
choice.grid(row=1, column=0)
window.mainloop()

最新更新