我试图找出为什么我不能将一个变量从一个小部件条目传递给一个变量,该变量是一个对象类中的用户名。
如上所述,它会抛出以下错误:TypeError:enter()缺少1个必需的位置参数:' 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()
我还尝试添加newUser = User。 init (自我,&#34;默认&#34; ...)它告诉我自己没有定义。我不确定我做错了什么。
答案 0 :(得分:1)
首先,在enter
函数中,如果没有类setUser()
的实例,则无法调用User
,因为它是成员函数。
其次,您应该将enter
函数包含为User类的成员函数。然后,您需要创建一个User对象并将按钮绑定到User.event
,而不只是event
。
此代码将正常运行。
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()