我已阅读有关id()
这项工作的文档
myvar='asd'
print id(myvar)
但是在这段代码中我无法理解它是如何工作的
from Tkinter import *
import time
import random
class pelota:
def __init__(self,canvas,raqueta,color):
self.canvas=canvas
self.raqueta=raqueta
self.id=canvas.create_oval(10,10,25,25, fill=color)
self.canvas.move(self.id,250,125)
empezar=[-5,-4,-3,-2,-1,1,2,3,4,5]
random.shuffle(empezar)
self.x=empezar[0]
self.y=-3
self.canvas_height = self.canvas.winfo_height()
self.canvas_width = self.canvas.winfo_width()
def golpea_raqueta(self, pos):
raqueta_pos = self.canvas.coords(self.raqueta.id)
if pos[2] >= raqueta_pos[0] and pos[0] <= raqueta_pos[2]:
if pos[3] >=raqueta_pos[1] and pos[3] <= raqueta_pos[3]:
我在谈论这个具体的路线
self.raqueta=raqueta
raqueta_pos = self.canvas.coords(self.raqueta.id)
id如何工作(self.raqueta.id)?
完整代码
from Tkinter import *
import time
import random
class pelota:
def __init__(self,canvas,raqueta,color):
self.canvas=canvas
self.raqueta=raqueta
self.id=canvas.create_oval(10,10,25,25, fill=color)
self.canvas.move(self.id,250,125)
empezar=[-5,-4,-3,-2,-1,1,2,3,4,5]
random.shuffle(empezar)
self.x=empezar[0]
self.y=-3
self.canvas_height = self.canvas.winfo_height()
self.canvas_width = self.canvas.winfo_width()
def golpea_raqueta(self, pos):
raqueta_pos = self.canvas.coords(self.raqueta.id)
if pos[2] >= raqueta_pos[0] and pos[0] <= raqueta_pos[2]:
if pos[3] >=raqueta_pos[1] and pos[3] <= raqueta_pos[3]:
return True
return False
def dibujar(self):
self.canvas.move(self.id,self.x,self.y)
pos = self.canvas.coords(self.id)
if pos[1]<=0:
self.y=3
if pos[0]<=0:
self.x=3
if pos[2]>= self.canvas_width :
self.x=-3
if self.golpea_raqueta(pos) == True:
self.y=-3
if pos[3] >= self.canvas_height :
self.y=-3
class raqueta:
def __init__(self,canvas,color):
self.canvas=canvas
self.id=self.canvas.create_rectangle(10,10,100,20, fill=color)
self.canvas.move(self.id , 200,300)
self.x = 0
self.canvas_width = self.canvas.winfo_width()
self.canvas.bind_all('<KeyPress-Left>', self.izqu)
self.canvas.bind_all('<KeyPress-Right>', self.dere)
def dibujar(self):
self.canvas.move(self.id,self.x,0)
pos = self.canvas.coords(self.id)
if pos[0]<=0:
self.x=0
if pos[0]>0:
self.x=0
elif pos[2]>=self.canvas_width:
self.x=0
def izqu(self,evt):
self.x=-20
def dere(self,evt):
self.x=20
vent= Tk()
vent.title('mipong')
vent.resizable(0,0)
vent.wm_attributes('-topmost',1)
canvas= Canvas(vent, width=500,height=500, bd=0,highlightthicknes=0)
canvas.pack()
vent.update()
raqueta= raqueta(canvas,'blue')
pelota=pelota(canvas,raqueta,'red')
#help(Tkinter.Canvas.winfo_height)
while 1:
pelota.dibujar()
raqueta.dibujar()
vent.update_idletasks()
vent.update()
time.sleep(0.01)
答案 0 :(得分:1)
在画布上创建项目时,它会返回唯一标识符。在您发布的代码中,您将标识符分配给self.id
。虽然名称类似于名为id
的内置函数,但它们完全不相关。
为避免混淆,您可以将self.id
重命名为self.canvas_id