Python NameError:未在类中定义名称[…]
我在tkinter中尝试使用入口小部件时遇到错误(需要获取Tictatcoe的玩家姓名)Python NameError:未在类中定义名称[…],python,class,tkinter,Python,Class,Tkinter,我在tkinter中尝试使用入口小部件时遇到错误(需要获取Tictatcoe的玩家姓名) 我已经创建了一个类播放器: class Player: """ Informations sur les joueurs """ def __init__(self): self.name = "" self.score = 0 self.active = 0 def get_name(self, main_window): name_selection_window =
我已经创建了一个类播放器:
class Player:
""" Informations sur les joueurs """
def __init__(self):
self.name = ""
self.score = 0
self.active = 0
def get_name(self, main_window):
name_selection_window = Toplevel()
name_selection_window.resizable(0,0)
name_selection_window.wait_visibility()
name_selection_window.grab_set()
name_selection_window.transient(main_window)
name_selection_window.focus_force()
player_name_label = Label(name_selection_window, text="Nom du Joueur 1 : ")
player_name_label.pack()
name_entry = Entry(name_selection_window, bd=3)
name_entry.bind("<Return>",self.entry_master)
name_entry.pack()
main_window.wait_window(name_selection_window)
def entry_master(self, event):
"""Récupère l'entrée pour chaque joueur."""
name = name_entry.get()
if name != "":
self.name = name
name_selection_window.destroy()
pass
我不明白为什么,因为name\u条目是在get\u name()中定义的。当我在类外同时使用get_name和entry_master时,它会起作用
你能帮我解决这个问题吗?谢谢Python非常擅长显式声明变量的位置。您可能希望将
name\u条目
作为实例变量。为此,请将name\u条目
的所有实例替换为self.name\u条目
self
引用当前对象,您希望将该对象保存在该对象中。否则,它只是一个局部变量。…因为它不是?您缺少了一些self
。为什么name\u entry
中的self变量不是get\u name
?因为您没有编写self.name\u entry
——Python并没有假设方法中的局部变量是您可能熟悉的其他一些语言的实例属性。要在实例方法中设置实例属性,您需要self
:self.foo=…
。要检索它,您仍然需要self:foo=self.foo
谢谢您的帮助!添加self之后。在需要每个变量之前,现在一切正常感谢您的解释,现在问题已经解决了;)@ThibaultJ很高兴听到这个消息!如果答案解决了问题,请记住将其标记为正确。@ThibaultJ答案旁边有一个复选标记,用于将该答案标记为正确,将问题标记为已解决。
Exception in Tkinter callback
Traceback (most recent call last):
File "c:\miniconda3\lib\tkinter\__init__.py", line 1549, in __call__
return self.func(*args)
File "N:\ISN\tictactoe\jeu_v2.py", line 32, in entry_master
name = name_entry.get()
NameError: name 'name_entry' is not defined