Error when choosing from random list in python
Question:
I am trying to choose a random adjective from a list and then displaying it as a label.
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()
When I run this code it returns this error in the “label2” line in the doit() function: TypeError: can only concatenate str (not "list") to str
I understand that I need to convert the list to a string, how do I do this?
Answers:
rchoice
is a list, so you can’t concatenate the string text1
with it. You should store the returning value of random.choice(rchoice)
in a variable and concatenate text1
with that variable instead:
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
I am trying to choose a random adjective from a list and then displaying it as a label.
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()
When I run this code it returns this error in the “label2” line in the doit() function: TypeError: can only concatenate str (not "list") to str
I understand that I need to convert the list to a string, how do I do this?
rchoice
is a list, so you can’t concatenate the string text1
with it. You should store the returning value of random.choice(rchoice)
in a variable and concatenate text1
with that variable instead:
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