This is my code:
from tkinter import *
import random
root = Tk()
numbers = [0,1,2,3,4,5]
global AdviseBox
AdviseBox = Text(root, width=110, height=10)
AdviseBox.pack(side=RIGHT, expand=YES, padx=5, pady=5)
AdviseBox.insert(INSERT, "Your random number is:",(numbers[random.randint(0, len(numbers) - 1)]), "\n\nHappy?")
root.mainloop()
But I want it to produce this in the text box:
Your random number is: [RANDOM NUMBER HERE]
Happy?
I have tested to see if a print statement works instead of inserting the text into the textbox, and the print statement is able to produce the desired output. However, it seems the issue is the textbox not being able to understand the part where I pick a number form the list. I tried with other variables and it was the same issue. I don't know what to do, I think I have tried everything! :(
The insert
method takes a variable number of arguments. The first argument is the index, the second is a string. The third, if there is one, is a tag. The fourth is a string, the fifth a tag, the sixth a string, the seventh a tag, and so on (index, string, tag, string, tag, string, ...)
Looking at this line of code:
AdviseBox.insert(INSERT, "Your random number is:",(numbers[random.randint(0, len(numbers) - 1)]), "\n\nHappy?")
... using multiple lines it's the same as this:
AdviseBox.insert(
INSERT, # index
"Your random number is:", # string
(numbers[random.randint(0, len(numbers) - 1)]), # tag
"\n\nHappy?" # string
)
What you need to do instead is catenate those last three together into a single string. It's easiest to do by using temporary variables. There's no value in trying to cram all of that code into a single statement. Plus, when you use multiple lines it becomes easier to debug because you can check all of the intermediate values.
For example:
number = random.randint(0, len(numbers)-1)
s = "Your random number is: {}\n\nHappy?".format(number)
AdviseBox.insert(INSERT, s)
Note: since you want to pick from an existing list of numbers, instead of random.randint
you can use random.choice which more closely reflects your intention:
number = random.choice(numbers)