gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:31:08 27 4
gpt4 key购买 nike

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

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

我知道我需要将列表转换为字符串,我该怎么做?

最佳答案

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

关于python - 从python中的随机列表中选择时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52851832/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com