首页 > 解决方案 > Tkinter 回调中的异常,TypeError:+ 的不支持的操作数类型:“int”和“str”

问题描述

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)

Tkinter 回调 Traceback 中的异常(最近一次调用最后一次):

文件“C:\Users\qldhv\AppData\Local\Programs\Python\Python39\lib\tkinter_init _.py ”,第 1892 行,调用 return self.func(*args) 文件“C:/Users/qldhv/ Desktop/컴사문/13/ㅇㅇ.py”,第 29 行,在 fire bullets.append(Ball(canvas, 10, "red", 100, 200, 10, 0)) 文件 "C:/Users/qldhv/Desktop /컴사문/13/ㅇㅇ.py",第 14 行,在init self.id=canvas.create_oval(x,y,x+size,y+size,fill=color) TypeError: unsupported operand type(s) for + :'int'和'str'

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

标签: pythontkintercanvas

解决方案


的定义Ball

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

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

看看这条线

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

这里你实际上通过了size="redand color=10,所以这条线创建的 Balls 实例现在有intascolorstrassize

它应该是

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))

推荐阅读