Kivy中使用Python的数字输入

问题描述 投票:1回答:1

我对Kivy非常陌生,并且找到了一个简单计算器here的在线示例,我想尝试使用Kivy示例〜/ examples / keyboard / main.py进行修改。在该示例中是数字键盘,但我似乎无法弄清楚如何使其代替标准键盘出现。帮助或建议将不胜感激。

这是我开始的内容:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
from kivy.core.window import Window
from kivy.uix.vkeyboard import VKeyboard
from kivy.properties import ObjectProperty
from kivy.uix.button import Button
from kivy.config import Config
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy import require
Builder.load_string("""
<KeyboardScreen>:
    displayLabel: displayLabel
    kbContainer: kbContainer
    BoxLayout:
        orientation: 'vertical'
        Label:
            size_hint_y: 0.15
            text: "Available Keyboard Layouts"
        BoxLayout:
            id: kbContainer
            size_hint_y: 0.2
            orientation:"horizontal"
            padding: 10
        Label:
            id: displayLabel
            size_hint_y: 0.15
            markup: True
            text: "[b]Key pressed[/b] - None"
            halign: "center"
        Button:
            text: "Back"
            size_hint_y: 0.1
            on_release: root.manager.current = "mode"
        Widget:
            # Just a space taker to allow for the popup keyboard
            size_hint_y: 0.5

<Calc>:
    # This are attributes of the class Calc now
    a: _a
    b: _b
    result: _result
    KeyboardScreen:
    AnchorLayout:
        anchor_x: 'center'
        anchor_y: 'top'
        ScreenManager:
            size_hint: 1, .9
            id: _screen_manager
            Screen:
                name: 'screen1'
                GridLayout:
                    cols:1
#                    TextInput:
                    Button:
                        id: _a
                        text: '3'
                        on_press:KeyboardScreen(name="keyboard")
#                    TextInput:
                    Button:
                        id: _b
                        text: '5'
                        on_press:KeyboardScreen(name="keyboard")
                    Label:
                        id: _result
                    Button:
                        text: 'sum'
                        # You can do the opertion directly
                        on_press: _result.text = str(int(_a.text) + int(_b.text))
                    Button:
                        text: 'product'
                        # Or you can call a method from the root class (instance of calc)
                        on_press: root.product(*args)
        Screen:
            name: 'screen2'
            Label:
                text: 'The second screen'
    AnchorLayout:
        anchor_x: 'center'
        anchor_y: 'bottom'
        BoxLayout:
            orientation: 'horizontal'
            size_hint: 1, .1
            Button:
                text: 'Go to Screen 1'
                on_press: _screen_manager.current = 'screen1'
            Button:
                text: 'Go to Screen 2'
                on_press: _screen_manager.current = 'screen2'""")

class Calc(FloatLayout):
    # define the multiplication of a function
    def product(self, instance):
        # self.result, self.a and self.b where defined explicitely in the     kv
        self.result.text = str(int(self.a.text) * int(self.b.text))

class KeyboardScreen(Screen):
    def __init__(self, **kwargs):
        super(KeyboardScreen, self).__init__(**kwargs)
#       self._add_keyboards()
        self.set_layout("numeric.json","numeric.json")
        self._keyboard = None

    def set_layout(self, layout, button):
        """ Change the keyboard layout to the one specified by *layout*. """
        kb = Window.request_keyboard(
        self._keyboard_close, self)
        if kb.widget:
        # If the current configuration supports Virtual Keyboards, this
        # widget will be a kivy.uix.vkeyboard.VKeyboard instance.
            self._keyboard = kb.widget
            self._keyboard.layout = layout
        else:
            self._keyboard = kb

        self._keyboard.bind(on_key_down=self.key_down,on_key_up=self.key_up)

    def _keyboard_close(self, *args):
        """ The active keyboard is being closed. """
        if self._keyboard:
            self._keyboard.unbind(on_key_down=self.key_down)
            self._keyboard.unbind(on_key_up=self.key_up)
            self._keyboard = None

    def key_down(self, keyboard, keycode, text, modifiers):
        """ The callback function that catches keyboard events. """
        self.displayLabel.text = u"Key pressed - {0}".format(text)

        # def key_up(self, keyboard, keycode):

    def key_up(self, keyboard, keycode, *args):
        """ The callback function that catches keyboard events. """
        # system keyboard keycode: (122, 'z')
        # dock keyboard keycode: 'z'
        if isinstance(keycode, tuple):
            keycode = keycode[1]
            self.displayLabel.text += u" (up {0})".format(keycode)

class TestApp(App):
    sm = None  # The root screen manager
    Config.set("kivy", "keyboard_mode", 'dock')
    Config.write()

    def build(self):
#           self.sm = ScreenManager()
#        self.sm.add_widget(KeyboardScreen(name="keyboard"))
        return Calc()

if __name__ == '__main__':
    TestApp().run()
python input kivy numeric
1个回答
0
投票

我知道这个问题是3年前提出的,但是自从我来到这里寻求类似的答案后,我想现在我应该回答了,因为我已经弄清楚了。幸运的是,它非常简单。

VKeyboard documentation有一节详细说明了如何使用自定义布局,这是keyboard example正在做的事情。

因此,为了更直接地回答您的问题,您需要做的是从键盘示例中获取numeric.json文件,并将其放在main.py旁边的目录中。

从那里,您只需要添加一个键盘设置功能即可抓住虚拟键盘并将layout属性设置为'numeric.json'。一个例子是

kb = Window.request_keyboard(self._keyboard_close, self)
if kb.widget:
    vkeyboard = kb.widget
    vkeyboard.layout = 'numeric.json'

另外,在台式机上,您需要指定要使用“对接”键盘。您可以通过使用keyboard_mode

设置kivy Config属性来执行此操作
Config.set("kivy", "keyboard_mode", 'dock')

并且由于将所有内容放在上下文中通常是有帮助的,因此下面是执行此操作的最小可重复测试应用程序。

import kivy
kivy.require("1.11.1")

from kivy.config import Config
Config.set("kivy", "keyboard_mode", 'dock')

from kivy.app import App
from kivy.core.window import Window
from kivy.uix.textinput import TextInput

class Calc(TextInput):
    def _keyboard_close(self):
        pass
    def setup_keyboard(self):
        kb = Window.request_keyboard(self._keyboard_close, self)
        if kb.widget:
            kb.widget.layout = 'numeric.json'

class TestApp(App):
    def build(self):
        root = Calc()
        root.setup_keyboard()
        return root

if __name__ == '__main__':
    TestApp().run()

© www.soinside.com 2019 - 2024. All rights reserved.