gpt4 book ai didi

python - 使用 Tkinter 时出现“self”未定义错误

转载 作者:行者123 更新时间:2023-12-01 03:28:44 25 4
gpt4 key购买 nike

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 函数中的某些内容,更改命令行,但每次都会出现错误。

最佳答案

慢一点:

在原始代码中,您正在调用 self 上的 create 方法,该方法未在作用域中声明。

您想要调用 phonebook 类的 create 方法,因此必须首先实例化后者。基本上是这样的:

p = phonebook(John, Doe, Evergreen Terrace, 12, Washington, 000)
p.create()

将按预期工作。在您的情况下,您通过另一个方法调用该方法,该方法将变为:

p = phonebook(...)
menubar.add_command(label = 'Anlegen', command = p.create)
<小时/>

旁注

在 Python 中,始终以大写字母开头命名您的类,例如 Phonebook。这将避免您混淆类和实例。

关于python - 使用 Tkinter 时出现“self”未定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41183965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com