简体   繁体   English

如何在Tkinter的Canvas中对角移动对象?

[英]How to move objects diagonally in Tkinter's Canvas?

How can I make an object move diagonally in a Tkinter canvas every time someone presses two arrow keys at the same time? 每当有人同时按下两个箭头键时,如何使对象在Tkinter画布中沿对角线移动? I'm creating a simple animation but it only moves up, down, left or right. 我正在创建一个简单的动画,但它只能向上,向下,向左或向右移动。 Here's the code I have: 这是我的代码:

from tkinter import *
import time
root = Tk()
canvas = Canvas(root, width=800, height=800)
square = canvas.create_rectangle(0,0,50,50,outline='red')


def right(event):
 for i in range(5):
  canvas.move(ball,1,0)
  canvas.update()

def left(event):
 for i in range(5):
  canvas.move(ball,-1,0)
  canvas.update()

def down(event):
 for i in range(5):
  canvas.move(ball,0,1)
  canvas.update()

def up(event):
 for i in range(5):
  canvas.move(ball,0,-1)
  canvas.update()

root.bind('<Right>', right)
root.bind('<Left>', left)
root.bind('<Down>', down)
root.bind('<Up>', up)

canvas.pack()
root.mainloop()

Keypresses in tkinter are individual events; tkinter中的按键是个别事件; to the exception of key modifiers (shift, control, alt), you cannot bind an action to the "simultaneous" pressing of two keys. 除了键修饰符(shift,control,alt)之外,你不能将动作绑定到“同时”按下两个键。

What you can do, is assign NE, SE, NW, SW moves to different keys. 您可以做的是将NE,SE,NW,SW移动到不同的键。

I assigned the control of the movements to the following keys: 我将运动控制分配给以下键:

Q W E
A   D
Z X C 

other changes: 其他变化:

  • It is best practice to avoid star imports. 避免星级进口是最佳做法。
  • It was not necessary to update the canvas each time; 没有必要每次都update画布; move already redraws the changes on the canvas. move已经重绘了画布上的更改。
  • I assigned a 'speed' to the object, removed the repeated calling of move in a loop, and use the speed to determine the distance to move. 我为物体指定了“速度”,移除了循环中重复调用的move ,并使用速度来确定移动的距离。
  • I renamed square to ball , so ball is defined. 我将square重命名为ball ,因此定义了ball

the code: 编码:

import tkinter as tk


root = tk.Tk()
canvas = tk.Canvas(root, width=800, height=800)
ball = canvas.create_rectangle(0, 0, 50, 50, outline='red')

speed = 5

def w(event):
    canvas.move(ball, speed, 0)

def e(event):
    canvas.move(ball, -speed, 0)

def s(event):
    canvas.move(ball, 0, speed)

def n(event):
    canvas.move(ball, 0, -speed)

def nw(e):
    canvas.move(ball, speed, -speed)

def sw(e):
    canvas.move(ball, speed, speed)

def ne(e):
    canvas.move(ball, -speed, -speed)

def se(e):
    canvas.move(ball, -speed, speed)

root.bind('<KeyPress-w>', n)
root.bind('<KeyPress-e>', nw)
root.bind('<KeyPress-d>', w)
root.bind('<KeyPress-c>', sw)
root.bind('<KeyPress-x>', s)
root.bind('<KeyPress-z>', se)
root.bind('<KeyPress-a>', e)
root.bind('<KeyPress-q>', ne)

canvas.pack()
root.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM