首页 > 解决方案 > 类型错误:insert_results() 缺少 1 个必需的位置参数:'ergebnisse'

问题描述

因为我被困在 OOP 中,如果你能帮助我,我会很好。我想这只是一个小问题,要么是错误的初始化,要么是我对 Python 中的 OOP 的了解。

所以我想在 Tkinter GUI 中单击我的按钮时执行一个函数。此函数将 dict 传递给我的 GUI 类中的方法,该方法将其添加到我拥有的文本小部件中。

我使用 Python 3.8,Tkinter 运行良好。

谢谢!

所以我的代码如下:

import time
import numpy as np
import matplotlib.pyplot as plt
import tkinter as tk
from tkinter import *
from googlesearch import search

def search_():
    url = "werkzeug.de"
    keywords = ["Tauchsäge", "tauchsäge", "tAuchSäge"]
    ergebnisse = {}
    for e in keywords:
        erg = search(e, num_results=10, lang="de")[1:]
        time.sleep(3)
        for i in erg:
            if url in i:
                ind = erg.index(i)
                ergebnisse[e] = ind
    g.insert_results(ergebnisse)


class GUI():
    def __init__(self):
        self.gui_init()
    def gui_init(self):
        # create tkinter window
        root = tk.Tk()
        # window titel
        root.title("SEO-Ranking Tool")
        # window size and position
        root.geometry("750x600+30+30")
        Label(root, text="URL").grid(row=0, sticky=W,padx=(10, 10))
        Label(root, text="Keywords (Mit komma getrennt)").grid(row=2, sticky=W,padx=(10, 10))
        e1 = Entry(root, width=40)
        e2 = Entry(root, width=40)
        e1.grid(row=1,sticky=W,padx=(10, 10))
        e2.grid(row=3,sticky=W,padx=(10, 10))
        w1 = Button(root, width=34, text="Auswertung", command=search_)
        w1.grid(row=5 ,sticky=W ,padx=(10,10), pady=10)
        excel = 0
        c1 = Checkbutton(root, text="Export to Excel", variable=excel).place(x=300, y=80)
        c2 = Checkbutton(root, text="Blabla", variable=excel).place(x=300, y=50)
        c3 = Checkbutton(root, text="Blabla", variable=excel).place(x=300, y=20)
        self.t1 = Text(root,height=28, width=90)
        self.t1.grid(row=7, padx=(10,10), pady=10)
        root.mainloop()

    def insert_results(self,ergebnisse):
        for i in ergebnisse:
            self.t1.insert(i)
g=GUI()

标签: python-3.xooptkinter

解决方案


您需要使用 的实例GUI,而不是类本身:g.insert_results(ergebnisse). 当您在类上调用它时,第一个参数被传递给self,因此没有参数被传递为ergebnisse


一旦你解决了这个问题,你就会遇到另一个问题。因为您在由 调用mainloop的函数内部调用__init__,并且因为mainloop永远不会返回,所以该类的实例永远不会完全初始化。因此,您将得到一个NameError: name 'g' is not defined因为__init__永远不会返回,这导致g尚未完全创建。

解决方案是将调用mainloop移出类,或者至少在创建类的实例后作为一个单独的步骤。

例如:

class GUI():
    def __init__(self):
        self.gui_init()

    def gui_init(self):
        self.root = tk.Tk()
        ...

    def start(self):
        self.root.mainloop()
...
g = GUI()
g.start()

推荐阅读