import tkinter as tk
root = tk.Tk()
root.title('Book')
class phonebook:
def __init__(self,first_name, last_name, street, postcode, city, number):
self.first_name = first_name
self.last_name = last_name
self.street = street
self.postcode = postcode
self.city = city
self.number = number
def create(self):
creation = tk.Tk()
tk.Label(creation, text = 'First Name').grid(row = 0, column = 0)
tk.Label(creation, text = 'Last Name').grid(row = 1, column = 0)
tk.Label(creation, text = 'Stadt').grid(row = 2, column = 0)
tk.Label(creation, text = 'Postleitzahl').grid(row = 3, column = 0)
tk.Label(creation, text = 'Straße').grid(row = 4, column = 0)
tk.Label(creation, text = 'Telefonnummer').grid(row = 5, column = 0)
self.first_name = tk.Entry(creation)
self.last_name = tk.Entry(creation)
self.street = tk.Entry(creation)
self.postcode = tk.Entry(creation)
self.city = tk.Entry(creation)
self.number = tk.Entry(creation)
menubar = tk.Menu(root)
root.config(menu = menubar)
menubar.add_command(label = 'Anlegen', command = self.create)
menubar.add_command(label = 'Bearbeiten')
menubar.add_command(label = 'Löschen')
menubar.add_command(label = 'Sortieren')
menubar.add_command(label = 'Suche')
menubar.add_command(label = 'Hilfe')
root.mainloop()
当我尝试上面的代码时,我收到此错误:
Traceback (most recent call last):
File "C:/Users/Lenovo M93p/Dropbox/Uni Dropbox/EPR/EPR_Blatt05_Jonas_Emrich_Karl_Wilhelm_Viebach/geathb.py", line 45, in <module>
menubar.add_command(label = 'Anlegen', command = self.create)
NameError: name 'self' is not defined
当我改变时:
menubar.add_command(label = 'Anlegen', command = self.create)
到:
menubar.add_command(label = 'Anlegen', command = phonebook.create)
我收到此错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Lenovo M93p\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1550, in __call__
return self.func(*args)
TypeError: create() missing 1 required positional argument: 'self'
我试图更改create
函数中的某些内容,更改命令行,但每次都会出错。
答案 0 :(得分:2)
不那么快:
在原始代码中,您在create
上调用self
方法,该方法未在范围内声明。
您想要调用create
类的phonebook
方法,因此必须首先实例化后者。基本上,这样的事情:
p = phonebook(John, Doe, Evergreen Terrace, 12, Washington, 000)
p.create()
将按预期工作。在您的情况下,您通过另一个方法调用该方法,该方法变为:
p = phonebook(...)
menubar.add_command(label = 'Anlegen', command = p.create)
旁注
在Python中,始终将您的类命名为以大写字母开头,例如Phonebook
。这样可以避免类和实例之间的混淆。