Reputation: 11
I am trying to figure out why I cannot pass a variable from a widget entry to a variable meant to be the username within a class of objects.
As written it throws the following error: TypeError: enter() missing 1 required positional argument: 'self'
class User:
'a class to define users'
def __init__(self, username, goal, contra, gender, weight):
self.username = username
self.goal = goal
self.contra = contra
self.gender = gender
self.weight = weight
'Adds date and current weight to an array to track progress'
#def weighIn[date, weight]:
def setUser(self, username):
self.username = string
def enter(self):
global e1
global string
string = e1.get()
setUser()
namescreen = Tk.Tk()
namescreen.title("Current Exercise")
var = StringVar()
label = Label( namescreen, textvariable=var)
var.set("Hi! What is your name?")
label.pack()
usr = StringVar()
e1 = Entry(namescreen, textvariable=usr)
e1.pack()
b1 = tkinter.Button(namescreen, text ="Enter", command =enter)
b1.pack()
namescreen.bind('<Return>', enter)
namescreen.mainloop()
I have also tried adding newUser = User.init(self, "Default"...) and it tells me that self is not defined. I am not sure what I am doing wrong.
Upvotes: 0
Views: 69
Reputation: 2274
First off, in your enter
function you cant call setUser()
without an instance of class User
because it's a member function.
Second, you should include the enter
function as a member function of class User. Then you need to create a User object and bind the button to User.event
and not just event
.
This code will run correctly though.
import Tkinter as Tk
class User:
'a class to define users'
def __init__(self, username, goal, contra, gender, weight):
self.username = username
self.goal = goal
self.contra = contra
self.gender = gender
self.weight = weight
'Adds date and current weight to an array to track progress'
#def weighIn[date, weight]:
def setUser(self, username):
self.username = string
print('Username is {}'.format(self.username))
def enter(self):
global e1
global string
string = e1.get()
self.setUser(string)
namescreen = Tk.Tk()
namescreen.title("Current Exercise")
user = User('','','','','')
var = Tk.StringVar()
label = Tk.Label( namescreen, textvariable=var)
var.set("Hi! What is your name?")
label.pack()
usr = Tk.StringVar()
e1 = Tk.Entry(namescreen, textvariable=usr)
e1.pack()
b1 = Tk.Button(namescreen, text ="Enter", command =user.enter)
b1.pack()
namescreen.bind('<Return>', user.enter)
namescreen.mainloop()
Upvotes: 1