Tkinter回调异常,TypeError:不支持+:'int'和'str'的操作数类型

2024-10-06 12:17:26 发布

您现在位置:Python中文网/ 问答频道 /正文

from tkinter import *

from time import sleep

import random                        

class Ball:

    def __init__(self, canvas, color, size, x, y, xspeed, yspeed):
        self.canvas = canvas 
        self.color = color 
        self.size = size 
        self.x = x 
        self.y = y 
        self.xspeed = xspeed 
        self.yspeed = yspeed
        self.id=canvas.create_oval(x,y,x+size,y+size,fill=color)
    def move(self): 
        self.canvas.move(self.id, self.xspeed, self.yspeed)
        (x1, y1, x2, y2)=self.canvas.coords(self.id)
        (self.x, self.y)=(x1, y1)
        if x1<=0 or x2>=WIDTH:         
            self.xspeed=-self.xspeed
        if y1<=0 or y2>=HEIGHT:
            self.yspeed=-self.yspeed

WIDTH=800

HEIGHT=400

bullets=[]

def fire(event):

    bullets.append(Ball(canvas, 10, "red", 100, 200, 10, 0))


window = Tk()

canvas = Canvas(window, width=WIDTH, height=HEIGHT)

canvas.pack()

canvas.bind("<Button-1>", fire)


spaceship = Ball(canvas, "green", 100, 100, 200, 0, 0)

enemy = Ball(canvas, "red", 100, 500, 200, 0, 5)


while True:

    for bullet in bullets:
        bullet.move()
        if (bullet.x+bullet.size) >= WIDTH:
            canvas.delete(bullet.id)
            bullets.remove(bullet)
    enemy.move()
    window.update()
    sleep(0.03)

Exception in Tkinter callback Traceback (most recent call last):

File "C:\Users\qldhv\AppData\Local\Programs\Python\Python39\lib\tkinter_init_.py", line 1892, in call return self.func(*args) File "C:/Users/qldhv/Desktop/컴사문/13/ㅇㅇ.py", line 29, in fire bullets.append(Ball(canvas, 10, "red", 100, 200, 10, 0)) File "C:/Users/qldhv/Desktop/컴사문/13/ㅇㅇ.py", line 14, in init self.id=canvas.create_oval(x,y,x+size,y+size,fill=color) TypeError: unsupported operand type(s) for +: 'int' and 'str'

单击时出错。我不知道原因


Tags: inimportselfidsizemovedefwidth
1条回答
网友
1楼 · 发布于 2024-10-06 12:17:26

Ball的定义是

def __init__(self, canvas, color, size, x, y, xspeed, yspeed):

因此,在从承包商创建实例时,我们必须按此特定顺序传递参数Ball()

查看这一行

 bullets.append(Ball(canvas, 10, "red", 100, 200, 10, 0))

这里您实际传递了size="redcolor=10,因此此行创建的Balls实例现在有int作为colorstr作为size

应该是

bullets.append(Ball(canvas, "red", 10, 100, 200, 10, 0))

否则,您可以使用

bullets.append(Ball(canvas=canvas, size=10, color="red", x=100, x=200, xspeed=10, yspeed=0))

相关问题 更多 >