我想要捕捉所有的关键笔画,或将一个键笔画与一个按钮相关联。此时,除了用户单击按钮外,在此游戏中没有任何用户输入。我想给每个按钮分配一个键盘字母。我也在玩pynput,但是由于这个程序已经在使用TKinter,我似乎应该能够用它的特性来完成它。
我可以在主游戏类中使用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()我在“游戏”类中添加了一个测试函数,它目前还没有启动。
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的graphic.py。
http://mcsp.wartburg.edu/zelle/python/graphics/graphics.pdf --参见类_BBox(GraphicsObject):获取常用方法。
我看到GraphWin类有一个任意键-它捕捉键。但是,我如何在我的主程序中返回它,特别是作为一个事件,用户一输入它就会触发它?
我需要写我自己的侦听器吗?参见python graphics win.getKey() function?…。那个帖子有一个等待键的时间循环。我不知道我会把这样一个while循环放在哪里,以及它将如何触发到"Game“类中来触发一个事件。我需要写我自己的听众吗?
发布于 2020-06-21 17:35:21
on_press()命令不触发的原因是.bind()调用绑定到Canvas实例。这意味着画布小部件必须具有键压注册的焦点。
使用bind_all而不是bind。
解决这一问题的替代办法:
使用def hit(self, event='')将字母h直接绑定到“命中”按钮处理函数(只需确保命中函数具有以下签名)的
mainWindow.bind_all("h", game.on_press) -将按键绑定到整个应用程序root.bind("h", game.on_press) -将按键绑定到根窗口(可能在这里toplevel更准确,取决于是否有多个窗口)与捕获任何键有关,这里有一些使用"<Key>"事件说明符:https://tkinterexamples.com/events/keyboard的示例。
发布于 2020-06-21 11:49:48
每当您想将鼠标和键盘输入与小部件结合起来时,我强烈建议您使用内置的.bind()方法。.bind()可以有两个值:
举个例子:
entry_name.bind("<Return>", function_name_here)只要按下键盘上的function_name_here()或Enter键,就会调用Return函数。几乎所有tk小部件都可以使用此方法。您还可以声明键组合以及鼠标控件。(Ctrl,左键单击等)。如果要将多个键笔画绑定到某个回调函数,那么只需使用相同的回调函数绑定两者:
entry_name.bind("<Return>", function_name_here)
entry_name.bind("<MouseButton-1>", function_name_here)这将允许您在按下鼠标的Return或鼠标左键时调用该函数。
https://stackoverflow.com/questions/62414224
复制相似问题