在python中从随机列表中选择时出错

2024-05-15 09:46:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从列表中随机选择一个形容词,然后将其显示为标签

from tkinter import*
import random

root = Tk()
root.geometry("500x500")
root.title("amazing")

    rchoice = ["is smart", " is dumb", " is ugl", " is ugly"]
    random.choice(rchoice)


    def doit():
        text1 = word.get()
        label2 = Label(root, text=text1 +rchoice, font=("Comic Sans MS", 20),  fg="purple").place(x=210, y=350)
        return


    word = StringVar()
    entry1 = Entry(root, textvariable=word, width=30)
    entry1.pack
    entry1.place(x=150, y=90)


    heading = Label(root, text="app of truth", font=("Comic Sans MS", 40), fg="brown").pack()
    Button = Button(root, text="buten", width=15, height=3, font=("Comic Sans MS", 20), fg="blue", bg="lightgreen", command=doit).pack(pady=90)

    root.mainloop()

当我运行此代码时,它在doit()函数的“label2”行中返回此错误:TypeError: can only concatenate str (not "list") to str

我知道我需要把列表转换成字符串,我该怎么做


Tags: textimport列表isrootpackwordms
1条回答
网友
1楼 · 发布于 2024-05-15 09:46:13

rchoice是一个列表,因此不能将字符串text1与之连接。应将返回值random.choice(rchoice)存储在变量中,并将text1与该变量连接起来:

rchoice = ["is smart", " is dumb", " is ugl", " is ugly"]
phrase = random.choice(rchoice)

def doit():
    text1 = word.get()
    label2 = Label(root, text=text1 + phrase, font=("Comic Sans MS", 20),  fg="purple").place(x=210, y=350)
    return

相关问题 更多 >