[英]Problem Destroying Button Tkinter, NameError
I am relatively new to programming with Python, and was building a fairly simple Rock Paper Scissors game with Tkinter.我对使用 Python 进行编程比较陌生,并且正在使用 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.基本上,我有一个按钮,调用此 function,在此 function 中,我想销毁我创建的按钮,但出现
NameError
。
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).
另外,我正在使用 3.8 解释器,并且现在还不想使用课程(我知道我将不得不很快开始学习它)。
global
variables in a python function simply allow a function to read and modify a variable in the global scope. python function 中的
global
变量只允许 function 读取和修改全局 Z31A1FD140BE4BEF2AECA81 中的变量。 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:假设您的
play()
function 是您第一次定义Rock
、 Paper
和Scissors
,您必须首先在任何 function 之外创建 3 个变量,如下所示:
Rock = None
Paper = None
Scissors = None
Then in your choose()
function, add the global variables, like this:然后在您的
choose()
function 中,添加全局变量,如下所示:
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:您必须在要使用该全局变量的每个 scope 中包含
global
关键字。这有效:
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:但一般来说,对于这样的事情,我会将对象作为参数传递给 function,即:
def choose(choice, paper, scissors):
if choice == "rock":
paper.destroy()
scissors.destroy()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.