【问题标题】:TypeError: search_country() takes 0 positional arguments but 1 was givenTypeError: search_country() 接受 0 个位置参数,但给出了 1 个
【发布时间】:2020-05-10 10:22:45
【问题描述】:

我使用 Tkinter 并且有一个条目和一个“搜索”按钮。如果我们在条目中输入文本并点击搜索按钮,效果会很好。它调用了一个名为 search_country 的函数。 但是,如果我们点击搜索按钮或只按 Enter,我想调用 search_country。然后我绑定这个:entry.bind('', search_country) 它显示了那个错误。

entry = Entry(win)
entry.grid(row=0, column=1)
entry.bind('<Return>', search_country)
button_search = Button(f2, text="Search", command= search_country)
button_search.grid(row=0, column=2)

def search_country(): 
    search_ = " ".join(entry.get().split()).title().replace('And','&')
    entry.delete(0,"end")    
    if search_ in countries:
        country_index= countries.index(search_)
        listbox.selection_clear(0, END)
        listbox.select_set(country_index)
        showimg(country_index)

我尝试了很多方法,但只得到了以下两种方法之一:点击按钮搜索或在条目中按 Enter。我需要两种方法正常工作。

谢谢。

【问题讨论】:

    标签: python button tkinter bind tkinter-entry


    【解决方案1】:

    当你这样做时

    entry.bind('<Return>', search_country)
    

    绑定函数获取event作为参数。

    因此您可能需要在绑定函数中添加此参数。

    def search_country(event): 
    

    一些文档https://effbot.org/tkinterbook/tkinter-events-and-bindings.htm

    【讨论】:

    • 当单击Search 按钮时调用相同的函数,它不需要回调函数的参数,那么它会引发错误。将函数签名改为def search_country(event=None):
    • 非常感谢您的回答。我会仔细阅读文档并再试一次。
    猜你喜欢
    • 2020-06-13
    • 2013-09-23
    • 2017-10-05
    • 2016-01-30
    • 2019-06-26
    • 2014-11-12
    • 2019-04-15
    • 1970-01-01
    相关资源
    最近更新 更多