I need to make the local variable in a class into a global variable. It gives an error if I try to make a local variable in a class global. As you can see in the code I would like to get the temp_username
and temp_username1
to be a global variable for later use but the class would not let me.
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()
Instead of using just temp_username, make use of static variable, that is TwoPlayers.temp_username and TwoPlayers.temp_username1 inside the print function.
You can also use self.temp_username and self.temp_username1, which indicates an instance variable.
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.