问题
I am new to python and trying to make a game where an object moves left/right according to the arrow keys on the keyboard. I've seen different methods to do this through importing turtle, curse, etc., but how do I do this using only win.getKey()
?
So far I have this, but it isn't working:
while True:
k = win.checkKey()
if k == 'Left':
object.move(-dx, dy)
elif k == 'Right':
object.move(dx, dy)
elif k == 'period':
break
回答1:
Since you only provided a fragment of code, I'm going to make some guesses as to what a MCVE might look like for this question:
from graphics import *
win = GraphWin("My Test", 100, 100)
my_object = Circle(Point(50, 50), 10)
my_object.draw(win)
dx, dy = 10, 0
while True:
k = win.checkKey()
if k == 'Left':
my_object.move(-dx, dy)
elif k == 'Right':
my_object.move(dx, dy)
elif k == 'period':
break
win.close()
If this is correct, then the code works fine on my system. Make sure to click on the graphics window that pops up before typing so that you're not typing at the console but rather to the graphics window that's expecting the arrow keys.
Also, avoid redefining Python built-in names like object
. It didn't affect the example in this case but it's something to watch for when things don't work as expected.
来源:https://stackoverflow.com/questions/41156910/python-graphics-win-getkey-function