【问题标题】:Error when choosing from random list in python从python中的随机列表中选择时出错
【发布时间】:2018-10-17 09:44:35
【问题描述】:

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

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

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

【问题讨论】:

    标签: python string list random choice


    【解决方案1】:

    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
    

    【讨论】:

    • 太棒了,成功了。我认为这会更难。
    猜你喜欢
    • 1970-01-01
    • 2012-02-21
    • 2012-11-01
    • 1970-01-01
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多