如何使用 tkinter 中的 mousex 和 mousey 坐标在屏幕上移动对象 [英] How do i move an object on the screen using the mousex and mousey coordinates in tkinter

查看:32
本文介绍了如何使用 tkinter 中的 mousex 和 mousey 坐标在屏幕上移动对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试相对于鼠标 x 和鼠标 y 坐标移动名为 char 的绿色对象,但我不知道如何移动.谁能帮我?如果您想知道我正在尝试制作单人游戏 agario 的版本.

I am trying to move the green object called char relative to the mouse x and mouse y coordinates but I don't know how. Can anyone help me? In case you are wondering i am trying to make a version of single player 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)

推荐答案

用鼠标移动绿色圆圈,需要将圆圈的位置绑定到鼠标移动事件.下面是一个例子,当鼠标在画布中时,圆圈总是以鼠标为中心:

To move the green circle with the mouse, you need to bind the position of the circle to mouse motion event. Here is an example where the circle is always centered on the mouse when the mouse is in the canvas:

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

这篇关于如何使用 tkinter 中的 mousex 和 mousey 坐标在屏幕上移动对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆