我总是收到一个类型错误,说我缺少 1 个必需的位置参数,即“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()
问题在这里:
button = Button(root, text="Create Group Chat", command= button_click)
注意命令 - 它说要调用
button_click
,并且将不带任何参数。您将点击功能定义为
def button_click(self):
所以当您单击按钮并调用
button_click
时没有参数,因为您的定义需要一个 self 参数 - 无论是因为它在一个类中还是出于任何原因 - 你都会得到错误。要么在参数中去掉self
def button_click():
或者如果它应该是类定义的一部分,则仅使用有效对象定义 Button。例如,你可以把里面
def __init__(self)
:
self.button = Button(root, text="Create Group Chat", command= self.button_click)
在构造函数中构建 GUI 的额外好处,这是一个很好的设计。
在类中放置
button_click
方法view
,一些关于自我的解释
class view():
...
def button_click(self):
self.form.destroy()
Chatclient().design()
您需要将 button_click() 的函数定义放在类中。
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()
基本上,您需要缩进函数定义的代码。
实际上,当您将函数的代码放在类中时,它就会成为该类的成员函数,并且通过传递参数 self,您实际上只是使用了对调用该函数的对象(类的实例)的引用.如果你知道的话,这就像 C++ 中的
this
。
您可以在这里阅读更多关于自我的信息。
您还需要缩进最后两行
button
。我通过注释掉我无法测试的任何内容来检查您的代码:
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.form.destroy()
print('test')
# Chatclient().design()
button = Button(root, text="Create Group Chat", command=button_click)
button.pack()
root.mainloop()
出局: