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'
单击时出错。我不知道原因
Ball
的定义是因此,在从承包商创建实例时,我们必须按此特定顺序传递参数
Ball()
查看这一行
这里您实际传递了
size="red
和color=10
,因此此行创建的Balls实例现在有int
作为color
和str
作为size
应该是
否则,您可以使用
相关问题 更多 >
编程相关推荐