gpt4 book ai didi

python - 当按下键盘上的按钮时,如何使方 block 移动? Tkinter, python

转载 作者:行者123 更新时间:2023-12-05 01:55:21 25 4
gpt4 key购买 nike

如何在按下键盘上的“d”按钮(例如)时让方 block 移动?

from tkinter import *
root = Tk()
root.title('Snake')
root["width"] = 400
root["height"] = 400

field = Canvas(root)

x = 0
y = 0

def snake(x, y):
field.create_rectangle(10, 20, 30, 40)
field.grid(row=x, column=y)
x += 1
y += 1
return(x, y)


root.bind("<KeyPress>", snake(x=x, y=y))

root.mainloop()

最佳答案

一个简单的方法是使用 event.char。它返回按下的按钮的字符。然后检查它是哪个按钮,如果是 w,a,s,d -

则移动它
from tkinter import *
root = Tk()
root.title('Snake')
root["width"] = 400
root["height"] = 400

field = Canvas(root)
rect = field.create_rectangle(10, 20, 30, 40)
field.grid(row=0, column=0)

def snake(event):
x = 0 # Default
y = 0
if event.char == 'w':
y = -10

if event.char == 'a':
x = -10

if event.char == 's':
y = 10

if event.char == 'd':
x = 10

field.move(rect,x,y)


root.bind("<Key>", snake)
root.mainloop()

关于python - 当按下键盘上的按钮时,如何使方 block 移动? Tkinter, python ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70258664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com