python graphics win.getKey() function?

杀马特。学长 韩版系。学妹 提交于 2021-01-29 03:19:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!