python-3.x TypeError:button_click()缺少1个必需的位置参数:'self'

kninwzqo  于 2023-05-23  发布在  Python
关注(0)|答案(4)|浏览(241)

我总是得到一个类型错误,说我缺少一个必需的位置参数,这是'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()
ghg1uchk

ghg1uchk1#

您需要将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,如果你知道的话。
你可以阅读更多关于self here的内容。

nzk0hqpo

nzk0hqpo2#

您还需要缩进最后两行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()

输出:

zhte4eai

zhte4eai3#

问题就在这里:

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的额外好处,这是一个很好的设计。

uxh89sit

uxh89sit4#

button_click方法放入类viewsome explication about self

class view():

    ...

    def button_click(self):
        self.form.destroy()
        Chatclient().design()

相关问题