【问题标题】:For loop inside a method : TypeError positional arguments方法内的 For 循环:TypeError 位置参数
【发布时间】:2023-03-11 11:20:01
【问题描述】:

我正在尝试使用 tkinter 使用类创建一个简单的 Gui。 但是我真的不明白如何使 for 循环在 count 方法中工作,谁能告诉我应该在哪里添加缺少的参数?

from tkinter import *
import time


class App:

    def __init__(self, master):
        self.container1 = Frame(master)
        self.container1.pack()
        self.button1 = Button(self.container1, text="count")
        self.button1.bind("<Button-1>", self.count)
        self.button1.pack()

    def count(self):
        for i in range(100):
            self.button1["text"] = str(i)
            time.sleep(1)


root = Tk()
Myapp = App(root)
root.mainloop()

错误是:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.5/tkinter/__init__.py", line 1553, in __call__
    return self.func(*args)
TypeError: count() takes 1 positional argument but 2 were given

【问题讨论】:

    标签: python class for-loop tkinter typeerror


    【解决方案1】:

    当你绑定一个事件时,一个位置参数event被提供给回调函数。

    将您的 count 方法更改为:

    def count(self, event):
    

    您还需要摆脱time.sleep(1),因为.sleep() 是一个阻塞调用,这意味着它将阻塞tkinter 主循环,从而导致您的程序无响应。

    【讨论】:

    • 所以每当我在有变量的地方定义函数时,我都必须使用事件作为位置参数?如果有多个呢?另外,你能建议我一种方法来替换 time.sleep() 吗?感谢您的帮助。
    • 您的函数必须排除位置参数,因为 tkinter 的事件绑定(当您编写 self.button1.bind("...", self.count) 时)会自动将事件参数传递给回调函数,它不必命名为 event,可能就是这个def count(self, _):。而对于time.sleep()的替换,可以尝试搜索tkinter的root.after()方法,如果还是有问题,有时间我可以写一个解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    • 2018-06-22
    • 2020-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多