我总是得到一个类型错误,说我缺少一个必需的位置参数,这是'self',我如何解决这个问题?
from tkinter import *
import tkinter
from client import*
root = tkinter.Tk()
class view():
root.geometry("250x300")
F1 =Frame()
L = Listbox(F1)
L.grid(row=0, column =0)
L.pack()
F = open("users.txt","r")
M = F.read()
cont = M.split()
for each in cont:
ind = each.find("#") + 1
L.insert(ind+1 ,each[ind:])
break
F.close()
F1.pack()
# strng_ind = -1
def button_click(self):
self.form.destroy()
Chatclient().design()
button = Button(root, text="Create Group Chat", command= button_click)
button.pack()
root.mainloop()
4条答案
按热度按时间ghg1uchk1#
您需要将button_click()的函数定义放在类中。
基本上,您需要缩进函数定义的代码。
实际上,当你把函数的代码放在类中时,它就变成了该类的成员函数,通过传递参数self,你实际上只是使用了对调用该函数的对象(类的示例)的引用。这就像C++中的
this
,如果你知道的话。你可以阅读更多关于self here的内容。
nzk0hqpo2#
您还需要缩进最后两行
button
。我检查了你的代码,注解掉了所有我不能测试的东西:输出:
zhte4eai3#
问题就在这里:
注意这个命令-它说调用
button_click
,并且不带参数。您将单击函数定义为因此,当您单击按钮并调用
button_click
而不带参数时,由于您的定义需要一个self参数-无论是因为它在类中还是出于其他原因-您都会得到错误。要么去掉参数中的self
或者,如果它应该是类定义的一部分,则只使用有效对象定义Button。例如,您可以在
def __init__(self)
中放置:在构造函数中构造GUI的额外好处,这是一个很好的设计。
uxh89sit4#
将
button_click
方法放入类view
,some explication about self中