问题描述:

I am a Python beginner, and I decided that I wanted to create a program over my summer holiday, before I did this however I decided I would make a small program before, to practice creating GUI's. I am working on a joke machine, that uses the random module to select a random integer that will decide which joke is displayed, however it seems to only ever output joke 3, regardless of how many times I run it.

I can't see any issues here, any advice?

joke_select = random.randint (1,3)

joke1 = "Why do you never see elephants hiding in trees?\n because they're really good at it!"

joke2 = "What is grey and can't climb a tree? \n A parking lot"

joke3 = "What is red and bad for your teeth?\n A brick"

if joke_select == '1':

joke_label = tkinter.Label (main, text = joke1)

elif joke_select == '2':

joke_label = tkinter.Label (main, text = joke2)

else:

joke_label = tkinter.Label (main, text = joke3)

def get_joke():

joke_label.pack ()

网友答案:
if joke_select == '1':

joke_select is only ever an integer, but you're comparing it to a string here. Try comparing to an integer instead.

if joke_select == 1:

Likewise for elif joke_select == '2':.

网友答案:

Your scripts looks for a string and you generate a number.

if joke_select == 1:
    joke_label = tkinter.Label (main, text = joke1)
elif joke_select == 2:
    joke_label = tkinter.Label (main, text = joke2)
else:
   joke_label = tkinter.Label (main, text = joke3)

will probably work

网友答案:

Just a piece of advice: there is no need for whitespace on such things as random.randint (1,3). It would be clearer to have this as random.randint(1,3). There are a few more places in your code where this also applies.

相关阅读:
Top