如何让 Tkinter Python 中的线条在鼠标更新时保持在原来的位置而不移动

问题描述 投票:0回答:1

我一直在测试一些代码,以便在一个单独的项目中为计算机科学课实现一个最终项目(所以忽略制作不佳的运动代码,我有更好的),基本的最终想法是制作一个可以绕着一个窗口移动,中间有一条线,这条线可以跟随鼠标,点击鼠标时会射出子弹杀死敌人。我正在使用 python 和 Tkinter。我当前遇到的主要问题是,当我尝试使用 canvas.move 移动线条,然后更新鼠标时,它会传送回屏幕中间的起始位置。在不更新鼠标的情况下,它可以很好地移动,但它也会保持在其原始位置,而不指向当前位置的鼠标。我对 Tkinter 很陌生,甚至对 Python 也有些陌生,但我有相当多的编码经验,尤其是 Java,所以如果可能的话,请解释任何 Tkinter 概念,就好像我不知道它们一样,但我很对一般编码知识充满信心。这是您可以帮助我的代码:

# importing tkinter and math for their porpoises
from tkinter import *
import math

# Declaring vars, width and height for the window and canvas, starting x and y for the line, line length, and default staring mouse positions for the equations that kinda but not really break without this idk it's weird
w = 600
h = 600
x, y = w//2, h//2
dist = 30
mousex, mousey = 0, 0

# tkinter setup
root = Tk()
root.title("Line Tests")
root.geometry("{}x{}".format(w, h))
photo = PhotoImage(file="icon.png")
root.iconphoto(False, photo)
root.resizable(False, False)
canvas = Canvas(root, bg="white", width=w, height=h)
canvas.pack()
# making the line
line = canvas.create_line(x, y, x, y+30, fill="red", width="5")

# movement functions
def left(event):
    x = -10
    y = 0
    canvas.move(line, x, y)
def down(event):
    x = 0
    y = -10
    canvas.move(line, x, y)
def right(event):
    x = 10
    y = 0
    canvas.move(line, x, y)
def up(event):
    x = 0
    y = 10
    canvas.move(line, x, y)
def move(event):
    # sets the global variables to x and y pos of the mouse
    mousex, mousey = event.x, event.y
    print('{}, {}'.format(mousex, mousey))
    # equation explanation here: https://www.desmos.com/calculator/gb1udr257b
    canvas.coords(line, x, y, x+math.cos(math.atan((mousey-y)/(mousex-x)))*((mousex-x)/abs(mousex-x))*dist, y+math.sin(math.atan((mousey-y)/(mousex-x)))*((mousex-x)/abs(mousex-x))*dist)

# it's just root binding different functions to events (keys, mouse movement)
root.bind('<Motion>', move)
root.bind('<Up>', up)
root.bind('<Down>', down)
root.bind('<Left>', left)
root.bind('<Right>', right)

# loops the script
root.mainloop()

如果您想要对我用于查找线的终点以使其不会击中鼠标的方程进行演示和错误解释,则 desmos 链接位于此处

我尝试将canvas.move更改为canvas.coords,但是每当我按下一个键时,它就会使线条消失。例如我变了

def left(event):
    x = -10
    y = 0
    canvas.move(line, x, y)

def left(event):
    x = -10
    y = 0
    canvas.coords(line, x, y, x+math.cos(math.atan((mousey-y)/(mousex-x)))*((mousex-x)/abs(mousex-x))*dist, y+math.sin(math.atan((mousey-y)/(mousex-x)))*((mousex-x)/abs(mousex-x))*dist)
    # The same equation as before (to find the ending point of the line, not just drawing it to the mouse)

我仍然相信这样的东西仍然是解决方案,或者可能是canvas.itemconfig的东西,但我似乎无法弄清楚。

python tkinter input trigonometry tkinter-canvas
1个回答
0
投票

移动线后我们需要向

move
函数添加新的 x, y 坐标

x, y = (canvas.coords(line)[:2])
.

并且一定要检查

mousex-x == 0
以消除分割时的错误。

© www.soinside.com 2019 - 2024. All rights reserved.