python - 类型错误:缺少一个必需的位置参数 'event'

标签 python tkinter typeerror

我正在制作一个绘画程序,但我一直遇到这个错误 但是,如果我更改 event.x/event.y 的定义位置,则会出现相同的错误,但子例程不同

代码如下:

class paint:
    def __init__(self,root,canvas):
        self.root = root
        self.mouse_press = False #mouse isnt being pressed

        self.canvas = canvas

        self.canvas.bind('<ButtonPress-1>',self.MouseDown) # when left click is pressed / down the subroutine MouseDown is opened 
        self.canvas.bind('<ButtonRelease-1>',self.MouseUp)#when left click is relased open the MouseUp subroutine         
     
    def MouseDown(self,event):
        self.x = event.x
        self.y = event.y

        self.mouse_press = True # mouse is pressed 
        self.poll() #calls the coodinates subroutine 

    def MouseUp(self,event):
        
        self.poll()
        self.mouse_press = False
        self.root.after_cancel(self.after_id)

    def poll(self):

        if self.mouse_press:
 
            canvas.create_oval(self.x,self.y, self.x+10, self.y+10 , fill = '#f6f65a',outline = '#f6f65a')
            self.after_id = self.root.after(10,self.MouseDown)


def colour_pick():
    colour_choose = colorchooser.askcolor()[1] #opens a colour picker and picks the colour
    print(colour_choose)
    return(colour_choose)

我是怎么称呼这个类(class)的

p = paint(root,canvas)
root.mainloop()

我不断收到的错误:

Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 839, in callit
    func(*args)
TypeError: paint.MouseDown missing 1 required positional argument: 'event'

最佳答案

您的函数 MouseDown 需要一个 event 参数,因为您是这样定义它的:

def MouseDown(self,event):

但是,当您从 after 调用该函数时,您没有传递此参数:

self.after_id = self.root.after(10,self.MouseDown)

由于 MouseDown 使用 event 对象中的数据,您将需要合成一个具有函数使用的属性的对象(即:.x.y) 或者您需要重写 MouseDown 以便它不需要 event 参数。

关于python - 类型错误:缺少一个必需的位置参数 'event',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70511324/

相关文章:

python 2.7 : Themed "common dialog" tkinter interfaces via Ttk?

typeerror - 解决_ivp错误: 'Required step size is less than spacing between numbers.'

Python 类型错误 : 'list' object cannot be interpreted as an integer

python - 将 Base64 字符串解码为字节数组

python - 如何删除 Tkinter 小部件放置?

python - Python 中 ProcessPoolExecutor 的运行调用次数不正确

Python 将图像插入 Tkinter 文本小部件

python - 类型错误:启动 Spyder 5.2.2 时出现预期字符串或类似字节的对象

python - 我的 python 程序不会在终端中执行或显示任何内容

python : Sum of numbers in different files