python - 同时按 2 个键可对角移动 tkinter?

标签 python tkinter

如何使用 2 个键在 Canvas 上移动物体?在有人告诉我我没有做一些研究之前,我已经做了。我之所以还在问这个问题,是因为我不知道他们在说什么。人们正在谈论我不知道的迷你状态和命令。

from tkinter import *

def move(x,y):
    canvas.move(box,x,y)

def moveKeys(event):
    key=event.keysym
    if key =='Up':
        move(0,-10)
    elif key =='Down':
    move(0,10)
    elif key=='Left':
    move(-10,0)
    elif key=='Right':
        move(10,0)

window =Tk()
window.title('Test')

canvas=Canvas(window, height=500, width=500)
canvas.pack()

box=canvas.create_rectangle(50,50,60,60, fill='blue')
canvas.bind_all('<Key>',moveKeys)

有什么方法可以让我同时移动 2 个键吗?我希望使用这种格式来完成,而不是使用迷你状态。

最佳答案

如果你说的“迷你状态”方法指的是这个答案( Python bind - allow multiple keys to be pressed simultaneously ),其实也不难理解。

请参阅下面的代码的修改和注释版本,它遵循这一理念:

from tkinter import tk

window = tk.Tk()
window.title('Test')

canvas = tk.Canvas(window, height=500, width=500)
canvas.pack()

box = canvas.create_rectangle(50, 50, 60, 60, fill='blue')

def move(x, y):
    canvas.move(box, x, y)

# This dictionary stores the current pressed status of the (← ↑ → ↓) keys
# (pressed: True, released: False) and will be modified by Pressing or Releasing each key
pressedStatus = {"Up": False, "Down": False, "Left": False, "Right": False}

def pressed(event):
    # When the key "event.keysym" is pressed, set its pressed status to True
    pressedStatus[event.keysym] = True

def released(event):
    # When the key "event.keysym" is released, set its pressed status to False
    pressedStatus[event.keysym] = False

def set_bindings():
    # Bind the (← ↑ → ↓) keys's Press and Release events
    for char in ["Up", "Down", "Left", "Right"]:
        window.bind("<KeyPress-%s>" % char, pressed)
        window.bind("<KeyRelease-%s>" % char, released)

def animate():
    # For each of the (← ↑ → ↓) keys currently being pressed (if pressedStatus[key] = True)
    # move in the corresponding direction
    if pressedStatus["Up"] == True: move(0, -10)
    if pressedStatus["Down"] == True: move(0, 10)
    if pressedStatus["Left"] == True: move(-10, 0)
    if pressedStatus["Right"] == True: move(10, 0)
    canvas.update()
    # This method calls itself again and again after a delay (80 ms in this case)
    window.after(80, animate)

# Bind the (← ↑ → ↓) keys's Press and Release events
set_bindings()

# Start the animation loop
animate()

# Launch the window
window.mainloop()

关于python - 同时按 2 个键可对角移动 tkinter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44074425/

相关文章:

python - 使用 Pandas 和 HD5/HDFStore 进行压缩

python - numpy 不能将行向量转置为列?

python - Tkinter:点击时移动到随机位置

linux - 如何在 linux 中构建 Tkinter GUI,就像在 window 中构建 exe 一样?

python - 当在 tkinter 中嵌入的两个 matplotlib 图形之间切换时,第一个图形上会出现一组额外的意外 x 轴标签和刻度

python - 如何在 python 中进行 alpha 抠图

python - flask 中的 "TypeError: ' bool 值 ' object is not callable"

python - 将 tkinter 输入与 WHERE 语句 SQLite 连接

使用 Tkinter 的 Python GUI 登录

python - AWS Sagemaker - PCA 模型未部署