我正在做游戏,我希望角色一直保持按住箭头键才能移动。
我尝试制作一个新按钮,但是我是python的新手,这很令人困惑。我也尝试过制作“保持按钮”和“释放按钮”功能,但这很令人困惑。
这是我的代码。
from tkinter import *
import time
import threading
window = Tk()
window.title("Making things move")
window.bind("<Escape>", lambda e: window.quit()) #binds escape key to close window
winwidth = window.winfo_screenwidth()
winheight = window.winfo_screenheight()
#making a canvas to input images
playground = Canvas(window, width=winwidth, height=winheight, bg="silver")
playground.pack(expand=YES, fill="both")
#making an image and placing it on the canvas
path1=PhotoImage(file="tank1FINAL.png")
tank1=playground.create_image(winwidth/2,winheight/2, image=path1)
path2=PhotoImage(file="tank1FLIP.png")
#tells what to do when keybind is used
def downKeyTank1(event):
for i in range(25):
playground.move(tank1, 0,2)
time.sleep(.025)
window.update()
def upKeyTank1(event):
for i in range(25):
playground.move(tank1, 0,-2)
time.sleep(.025)
window.update()
def leftKeyTank1(event):
#flips the image when key is pressed
global path1, path2, tank1
x, y =playground.coords(tank1)
playground.delete(tank1)
tank1 =playground.create_image(x, y, image=path2)
#makes image move continuously
for i in range(50):
playground.move(tank1, -1,0)
time.sleep(.025)
window.update()
def rightKeyTank1(event):
global path1, path2, tank1
x, y =playground.coords(tank1)
playground.delete(tank1)
tank1 =playground.create_image(x, y, image=path1)
for i in range(50):
playground.move(tank1, 1, 0)
time.sleep(.025)
window.update()
#creates a keybind to movement
playground.bind_all('<Up>', upKeyTank1)
playground.bind_all('<Left>', leftKeyTank1)
playground.bind_all('<Right>', rightKeyTank1)
playground.bind_all('<Down>', downKeyTank1)
window.mainloop()
一些错误消息,与问题无关。
答案 0 :(得分:0)
您可以使用<KeyPress>
和<KeyRelease>
来获取按键的按下时间和按键的释放时间。您可以使用它为变量True
,False
move_up
或move_down
您可以after()
运行将检查这些变量并移动储罐的功能。
import tkinter as tk
# --- functions ---
def move():
if move_down:
playground.move(tank1, 0, 2)
if move_up:
playground.move(tank1, 0, -2)
if move_left:
playground.move(tank1, -2, 0)
if move_right:
playground.move(tank1, 2, 0)
window.after(20, move)
def key_pressed(event):
global move_down
global move_up
global move_left
global move_right
if event.keysym == 'Up':
move_up = True
if event.keysym == 'Down':
move_down = True
if event.keysym == 'Left':
move_left = True
if event.keysym == 'Right':
move_right = True
def key_released(event):
global move_down
global move_up
global move_left
global move_right
if event.keysym == 'Up':
move_up = False
if event.keysym == 'Down':
move_down = False
if event.keysym == 'Left':
move_left = False
if event.keysym == 'Right':
move_right = False
# --- main ---
move_down = False
move_up = False
move_left = False
move_right = False
window = tk.Tk()
playground = tk.Canvas(window)
playground.pack(expand=True, fill="both")
tank1 = playground.create_rectangle((0,0,10,10))
playground.bind_all('<KeyPress>', key_pressed)
playground.bind_all('<KeyRelease>', key_released)
move()
window.mainloop()