我需要将类中的局部变量转换为全局变量。如果我尝试在全局类中创建局部变量,则会出现错误。正如您在代码中看到的那样,我希望将temp_username
和temp_username1
用作全局变量以供以后使用,但该类不允许我使用。
class TwoPlayers:
def __init__(self, master):
self.master = master
self.top_frame = tk.Frame(self.master, relief="solid")
self.top_frame.pack(side="top", fill="none", expand=True)
self.label_1 = tk.Label(self.top_frame, text="Player1 Name: ")
self.label_1.grid(row=0, column=0, sticky="w", padx=5, pady=5)
self.label_1 = tk.Label(self.top_frame, text="Player2 Name: ")
self.label_1.grid(row=1, column=0, sticky="w", padx=5, pady=5)
self.username_entry = tk.Entry(self.top_frame, width=20)
self.username_entry .grid(row=0, column=1, padx=5, pady=5)
self.username_entry1 = tk.Entry(self.top_frame, width=20)
self.username_entry1 .grid(row=1, column=1, padx=5, pady=5)
self.save_button = tk.Button(self.top_frame, text="Save", command=lambda: self.read_username())
self.save_button.grid(row=4, column=0, columnspan=2, pady=20)
self.name_valid = False
self.username = None
def read_username(self):
temp_username = self.username_entry.get()
temp_username1 = self.username_entry1.get()
if temp_username == '':
print("No valid name")
return
else:
self.name_valid = True
self.username = temp_username
self.username1 = temp_username1
print(temp_username) #Shows the input name of the player can be deleted later
print(temp_username1)
self.master.destroy()
答案 0 :(得分:0)
使用静态变量,而不是仅使用temp_username,即打印功能中的TwoPlayers.temp_username和TwoPlayers.temp_username1。
您还可以使用self.temp_username和self.temp_username1来表示实例变量。