【问题标题】:Press 2 keys at once to move diagonally tkinter?一次按 2 个键对角移动 tkinter?
【发布时间】:2017-05-19 16:01:15
【问题描述】:

如何使用 2 个键在画布上移动某些东西?在有人告诉我我没有做一些研究之前,我做了。我仍然问这个的原因是因为我不知道他们在说什么。人们在谈论我不知道的迷你状态和命令。

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)

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

【问题讨论】:

  • 您不能使用您指定的格式来执行此操作。 tkinter 中的事件处理程序将始终响应单个按键。如果约束是你不能使用“迷你状态”,那么你就不能这样做。

标签: python tkinter


【解决方案1】:

如果你说的“迷你状态”方法是指这个答案(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()

【讨论】:

  • 你认为 13 岁孩子的大脑能够处理这个问题吗?
  • 好吧,您可以从运行代码开始,看看它是否符合您的要求。然后尝试一次更改一行,直到您对结果满意为止:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-16
  • 1970-01-01
  • 2021-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多