是否可以使线条在 tkinter 中沿对角线移动?

Is it possible to make the lines move diagonally in tkinter?

在下面这个程序中,我可以左右、上下移动线条。但是,是否可以使线条沿对角线移动?例如,当同时按下向上箭头和向右箭头时,程序会生成一条对角线移动 NE?

from tkinter import *


canvas_height = 400
canvas_width = 600
canvas_colour = "orange"
p1_x = canvas_width / 2
p1_y = canvas_height
p1_colour = "black"
line_width = 10
line_length = 10


def p1_move_N(event):
    global p1_y
    canvas.create_line(p1_x, p1_y, p1_x, (p1_y - line_length),
                       width=line_width, fill=p1_colour)
    p1_y = p1_y - line_length


def p1_move_S(event):
    global p1_y
    canvas.create_line(p1_x, p1_y, p1_x, p1_y + line_length,
                       width=line_width, fill=p1_colour)
    p1_y = p1_y + line_length


def p1_move_E(event):
    global p1_x
    canvas.create_line(p1_x, p1_y, p1_x + line_length, p1_y,
                       width=line_width, fill=p1_colour)
    p1_x = p1_x + line_length


def p1_move_W(event):
    global p1_x
    canvas.create_line(p1_x, p1_y, p1_x - line_length, p1_y,
                       width=line_width, fill=p1_colour)
    p1_x = p1_x - line_length


def erase_all(event):
    canvas.delete(ALL)

window = Tk()
window.title("Drawing Software")
canvas = Canvas(bg=canvas_colour, height=canvas_height,
                width=canvas_width, highlightthickness=0)
canvas.pack()

window.bind("<Up>", p1_move_N)
window.bind("<Down>", p1_move_S)
window.bind("<Left>", p1_move_W)
window.bind("<Right>", p1_move_E)

添加这样的函数:

def p1_move_NE(event):
    global p1_y,p1_x
    canvas.create_line(p1_x, p1_y, p1_x + line_length, (p1_y - line_length),
                   width=line_width, fill=p1_colour)
    p1_x = p1_x + line_length
    p1_y = p1_y - line_length

然后绑定:

window.bind("9", p1_move_NE)

我对您的程序的其他建议是使用 classes 和类似的通用函数:

def p1_move(dx, dy):
    global p1
    canvas.create_line(p1[0], p1[1], p1[0] + dx, p1[1] + dy,
                   width=line_width, fill=p1_colour)
    p1 = (p1[0] + dx, p1[1] + dy)

(我在示例中使用了元组 p1,但 class 点会更好。)