首页 > 解决方案 > NameError: name 'Pick' is not defined

问题描述

I am a learning the if statement by creating a rock, paper, scissors game with Tkinter. I'm trying to make a label that will appear if a button is pressed. so for example it will put a label saying "rock" if i press the rock button. But I have a problem in the if statement. This is what I have

import random
from tkinter import *

click = True

def compick():
    choice = random.choice(["rock","paper","scissors"])
    return choice

compchoice = compick()

def yourChoice(Pick):
    global click

br = Button(gui, image=img1, command= lambda:yourChoice('rock'))
br.place(x=15, y=100)
bp = Button(gui, image=img2, command= lambda:yourChoice('paper'))
bp.place(x=200 ,y=100)
bs = Button(gui, image=img3, command= lambda:yourChoice('scissors'))
bs.place(x=350, y=100)

if click==True:
    if Pick =='rock':
        LR.place(x=225, y=500)
        if compchoice =='rock':
            LR.place(x=225, y=15)

gui.mainloop()

It gave me an error saying "name 'Pick' is not defined". I have no idea what's wrong with the code.

标签: pythonif-statementtkinter

解决方案


Seems like an indentation error. Place all your code for the function yourChoice under a single indent.

Something like this:

def yourChoice(Pick):
    global click

    br = Button(gui, image=img1, command= lambda:yourChoice('rock'))
    br.place(x=15, y=100)
    bp = Button(gui, image=img2, command= lambda:yourChoice('paper'))
    bp.place(x=200 ,y=100)
    bs = Button(gui, image=img3, command= lambda:yourChoice('scissors'))
    bs.place(x=350, y=100)

    if click==True:
        if Pick =='rock':
           LR.place(x=225, y=500)
            if compchoice =='rock':
                LR.place(x=225, y=15)

Now, all of the above mentioned code is executed when a call is made to the yourChoice function.


推荐阅读