我正在尝试相对于鼠标x和鼠标y坐标移动名为char的绿色对象,但我不知道如何。谁能帮我?如果你想知道我正在尝试制作单人游戏agario的版本。
from tkinter import *
import random
from random import uniform, randrange
import time
#left,top,right,bottom
tk = Tk()
canvas = Canvas(tk,width=600,height=600)
canvas.pack()
pointcount = 0
char = canvas.create_oval(400,400,440,440,fill="green")
pos1 = canvas.coords(char)
x = canvas.canvasx()
y = canvas.canvasy()
class Ball:#ball characteristics#
def __init__(self,color,size):
self.shape = canvas.create_oval(10,10,50,50,fill=color)
self.xspeed = randrange(-5,7)
self.yspeed = randrange(-5,7)
def move(self):#ball animation#
global pointcount
canvas.move(self.shape,self.xspeed,self.yspeed)
pos = canvas.coords(self.shape)
if pos[0] <= 0 or pos[2] >= 600:#if ball hits the wall#
self.xspeed = -self.xspeed
if pos[1] <= 0 or pos[3] >= 600:
self.yspeed = -self.yspeed
left_var = abs(pos[0] - pos1[0])
top_var = abs(pos[1] - pos1[1])
if left_var == 0 and top_var == 0:
pointcount = pointcount + 1
print(pointcount)
colors = ["red","blue","green","yellow","purple","orange"]
balls = []
for i in range(10):
balls.append(Ball(random.choice(colors),50))
while True:
for ball in balls:
ball.move()
tk.update()
time.sleep(0.01)
答案 0 :(得分:0)
要使用鼠标移动绿色圆圈,您需要将圆圈的位置绑定到鼠标移动事件。下面是一个示例,当鼠标位于画布中时,圆圈始终以鼠标为中心:
from tkinter import *
root = Tk()
canvas = Canvas(root)
canvas.pack(fill="both", expand=True)
char = canvas.create_oval(400,400,440,440,fill="green")
def follow_mouse(event):
""" the center of char follows the mouse """
x, y = event.x, event.y
canvas.coords(char, x - 20, y - 20, x + 20, y + 20)
# bind follow_mouse function to mouse motion events
canvas.bind('<Motion>', follow_mouse)
root.mainloop()