我对 Kivy 和 Python 非常陌生。几周后。
我正在尝试创建一个计数器,它将接受用户输入(通过击键)来增加值。我尝试了各种代码,但我似乎无法得到正确的结果。这就是我现在所拥有的。我在 on_key_down 函数上遇到的麻烦最多。我按“p”键但没有任何反应。
main.py
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.properties import ObjectProperty
from kivy.core.window import Window
class MyLayout(GridLayout):
def __init__(self, **kwargs):
super(MyLayout, self).__init__(**kwargs)
self.total_count = 0 # Initialize the total count
def increment_total_count(self, instance):
# Function to increment total count and update label
self.total_count += 1
self.ids.total_counter.text = str(self.total_count)
def on_key_down(self, window, keycode, text, modifiers, is_repeat, *args):
if isinstance(keycode, (list, tuple)) and len(keycode) > 1: #added because I kept getting an 'int' error when pressing 'p'
if keycode[1] == 'p': # If you hit the key 'p'
self.ids.increment_button.dispatch('on_release')
class Counter(App):
def build(self):
root = MyLayout()
Window.bind(on_key_down = root.on_key_down)
return root
if __name__ == "__main__":
Counter().run()
.kv 文件
GridLayout:
cols: 2
Label:
id: total_counter
text: "0"
Button:
id: increment_button
text: "Increment"
on_release: root.increment_total_count(self) # Run increment_total_count from main.py
我得到了鼠标点击按钮;但希望用户能够按“p”键来触发与按钮相同的功能。
提前感谢您的帮助!
尝试将您的
on_key_down()
方法替换为:
def on_key_down(self, window, keycode, text, modifiers, is_repeat, *args):
if Keyboard.keycodes['p'] == keycode:
self.ids.increment_button.dispatch('on_release')
这需要导入
Keyboard
:
from kivy.core.window import Window, Keyboard