Nea*_*ers 3 keyboard-shortcuts tkinter python-3.x
我想捕获所有击键,或者将击键与按钮相关联。此时,除了用户点击按钮之外,该游戏中没有用户输入。我想为每个按钮分配一个键盘字母。我也在玩 pynput,但由于该程序已经在使用 TKinter,似乎我应该能够用它的功能来完成它。
我可以在主 Game 类中有一个 on_press 方法,然后为每个键调用适当的函数(与用户单击键相同),或者可能有更好的方法。
我见过的大多数示例都处理从 tkinter 类创建的对象,但在这种情况下,它从我的主程序中删除了几个级别。
这是我从 GitHub 上得到的一款游戏,并适应了我的喜好。所以我试图在结构上尽可能少地改变它。
在 Graphics.py 中,我看到以下代码:
class GraphWin(tk.Canvas):
    def __init__(self, title="Graphics Window", width=200, height=200):
        master = tk.Toplevel(_root)
        master.protocol("WM_DELETE_WINDOW", self.close)
        tk.Canvas.__init__(self, master, width=width, height=height)
        self.master.title(title)
        self.pack()
        master.resizable(0,0)
        self.foreground = "black"
        self.items = []
        self.mouseX = None
        self.mouseY = None
        self.bind("<Button-1>", self._onClick)  #original code
        self.height = height
        self.width = width
        self._mouseCallback = None
        self.trans = None
    def _onClick(self, e):
        self.mouseX = e.x
        self.mouseY = e.y
        if self._mouseCallback:
            self._mouseCallback(Point(e.x, e.y)) 
主程序基本上是这样的:
def main():
    # first number is width, second is height
    screenWidth = 800
    screenHeight = 500
    mainWindow = GraphWin("Game", screenWidth, screenHeight)
    game = game(mainWindow)
    mainWindow.bind('h', game.on_press())  #<---- I added this 
    #listener = keyboard.Listener(on_press=game.on_press, on_release=game.on_release)
    #listener.start()
    game.go()
    #listener.join()
    mainWindow.close()
if __name__ == '__main__':
    main()
我在 Game 类中添加了一个测试函数,它目前没有触发。
def on_press(self):
    #print("key=" + str(key))
    print( "on_press")
    #if key == keyboard.KeyCode(char='h'):
    #    self.hit()
按钮设置如下:
def __init__( self, win ): 
    # First set up screen
    self.win = win
    win.setBackground("dark green")
    xmin = 0.0
    xmax = 160.0
    ymax = 220.0
    win.setCoords( 0.0, 0.0, xmax, ymax )
    self.engine = MouseTrap( win )
然后后来...
self.play_button = Button( win, Point(bs*8.5,by), bw, bh, 'Play')
self.play_button.setRun( self.play )
self.engine.registerButton( self.play_button )
最后,按钮代码在 guiengine.py 中
class Button:
    """A button is a labeled rectangle in a window.
    It is activated or deactivated with the activate()
    and deactivate() methods. The clicked(p) method
    returns true if the button is active and p is inside it."""
    def __init__(self, win, center, width, height, label):
        """ Creates a rectangular button, eg:
        qb = Button(myWin, Point(30,25), 20, 10, 'Quit') """ 
        self.runDef = False
        self.setUp( win, center, width, height, label )
    def setUp(self, win, center, width, height, label):
        """ set most of the Button data - not in init to make easier
        for child class methods inheriting from Button.
        If called from child class with own run(), set self.runDef""" 
        w,h = width/2.0, height/2.0
        x,y = center.getX(), center.getY()
        self.xmax, self.xmin = x+w, x-w
        self.ymax, self.ymin = y+h, y-h
        p1 = Point(self.xmin, self.ymin)
        p2 = Point(self.xmax, self.ymax)
        self.rect = Rectangle(p1,p2)
        self.rect.setFill('lightgray')
        self.rect.draw(win)
        self.label = Text(center, label)
        self.label.draw(win)
        self.deactivate()
    def clicked(self, p):
        "Returns true if button active and p is inside"
        return self.active and \
               self.xmin <= p.getX() <= self.xmax and \
               self.ymin <= p.getY() <= self.ymax
    def getLabel(self):
        "Returns the label string of this button."
        return self.label.getText()
    def activate(self):
        "Sets this button to 'active'."
        self.label.setFill('black')
        self.rect.setWidth(2)
        self.active = True
    def deactivate(self):
        "Sets this button to 'inactive'."
        self.label.setFill('darkgrey')
        self.rect.setWidth(1)
        self.active = False
    def setRun( self, function ):
        "set a function to be the mouse click event handler"
        self.runDef = True
        self.runfunction = function
    def run( self ):
       """The default event handler.  It either runs the handler function
       set in setRun() or it raises an exception."""
       if self.runDef:
           return self.runfunction()
       else:
           #Neal change for Python3
           #raise RuntimeError, 'Button run() method not defined'
           raise RuntimeError ('Button run() method not defined')
           return False  # exit program on error
要求额外的代码:
class Rectangle(_BBox):
    def __init__(self, p1, p2):
        _BBox.__init__(self, p1, p2)
    def _draw(self, canvas, options):
        p1 = self.p1
        p2 = self.p2
        x1,y1 = canvas.toScreen(p1.x,p1.y)
        x2,y2 = canvas.toScreen(p2.x,p2.y)
        return canvas.create_rectangle(x1,y1,x2,y2,options)
    def clone(self):
        other = Rectangle(self.p1, self.p2)
        other.config = self.config
        return other
class Point(GraphicsObject):
    def __init__(self, x, y):
        GraphicsObject.__init__(self, ["outline", "fill"])
        self.setFill = self.setOutline
        self.x = x
        self.y = y
    def _draw(self, canvas, options):
        x,y = canvas.toScreen(self.x,self.y)
        return canvas.create_rectangle(x,y,x+1,y+1,options)
    def _move(self, dx, dy):
        self.x = self.x + dx
        self.y = self.y + dy
    def clone(self):
        other = Point(self.x,self.y)
        other.config = self.config
        return other
    def getX(self): return self.x
    def getY(self): return self.y
更新
我在评论中的一些注释:它使用的是:http : //mcsp.wartburg.edu/zelle/python/graphics.py John Zelle 的graphics.py。
http://mcsp.wartburg.edu/zelle/python/graphics/graphics.pdf - 参见 class _BBox(GraphicsObject): 了解常用方法。
我看到 GraphWin 类有一个 anykey - 它捕获密钥。但是我如何在我的主程序中恢复它,尤其是当用户输入它时会立即触发的事件?
我是否需要编写自己的侦听器 - 另请参阅python graphics win.getKey() 函数?…… 该帖子有一个等待按键的 while 循环。我不确定我会在哪里放置这样的 while 循环,以及如何触发“游戏”类来触发事件。我需要编写自己的监听器吗?
on_press()命令未触发的原因是.bind()调用绑定到 的实例Canvas。这意味着画布小部件必须具有按键才能注册的焦点。
使用bind_all代替bind。
解决此问题的替代方法:
使用mainWindow.bind_all("h", hit)- 将字母 h 直接绑定到“hit”按钮处理函数(只需确保 hit 函数具有如下签名:
def hit(self, event='')
使用mainWindow.bind_all("h", game.on_press)- 将按键绑定到整个应用程序
使用root.bind("h", game.on_press)- 将按键绑定到根窗口(toplevel根据是否有多个窗口,这里可能更准确)
与捕获任何键相关,这里有一些关于使用"<Key>"事件说明符执行此操作的示例:https : //tkinterexamples.com/events/keyboard/keyboard.html
| 归档时间: | 
 | 
| 查看次数: | 227 次 | 
| 最近记录: |