I am relatively new to programming with Python, and was building a fairly simple Rock Paper Scissors game with Tkinter. Basically, I have a button, that calls this function, and in this function, I want to destroy the button that I had created, but a NameError
arises.
Here is the relative code:
def choose(choice):
if choice == "rock":
Paper.destroy()
Scissors.destroy()
def play():
global Rock
Rock = Button(root, image = rock_photo, padx = 30, pady = 10, bg = "#fcf003", command = lambda: choose("rock"))
global Paper
Paper = Button(root,image = paper_photo, padx = 30, pady = 10, bg = "#c603fc", command=lambda: choose("paper"))
global Scissors
Scissors = Button(root,image = scissor_photo, padx = 30, pady = 10, bg = "#39fc03", command=lambda: choose("scissors"))
Rock.grid(row = 1, column = 0)
Paper.grid(row = 1, column = 2)
Scissors.grid(row = 1, column = 1)
play()
Furthermore, the Error:
NameError: name 'Paper' is not defined
Please let me know if I need to provide any more information. Also, I am using a 3.8 Interpreter and would like to not use classes just yet(I'm aware I'll have to start learning it soon).
global
variables in a python function simply allow a function to read and modify a variable in the global scope. It does not create a variable. Assuming that your play()
function is the first time that you define Rock
, Paper
, and Scissors
, you must first create 3 variables outside of any function like this:
Rock = None
Paper = None
Scissors = None
Then in your choose()
function, add the global variables, like this:
def choose(choice):
global Rock
global Paper
global Scissors
if choice == "rock":
Paper.destroy()
Scissors.destroy()
You have to include the global
keyword in every scope you want to use that global variable in. This works:
def choose(choice):
global Paper
global Scissors
if choice == "rock":
Paper.destroy()
Scissors.destroy()
But generally, for things like these, I would pass the objects as parameters to the function instead, that is:
def choose(choice, paper, scissors):
if choice == "rock":
paper.destroy()
scissors.destroy()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.