【发布时间】:2014-06-26 13:16:03
【问题描述】:
我正在使用 kivy 制作一个简单的计算器,并且我正在尝试使用 TextInput 作为屏幕。我不确定哪个
在TextInput 或Label 之间会更好,但TextInput 似乎是更好的选择(也许我错了?)。
GUI 基本就位,所有按钮都有各自的文本字段('0', '1', '2', '+', '='... 等)。每一次
用户按下一个按钮,该按钮的文本被添加到calc_string,当按下'='按钮时,
将被“评估”。本质上,一切正常,但我的输出都被打印到控制台,因为我无法得到字符串
插入TextInput 屏幕。我试图在由触发的回调(screen_callback)中设置TextInput 的文本
绑定到TextInput 的on_property 方法。它不工作。我怎样才能做到这一点?可能吗?
main.py:
#!/usr/bin/env python
import kivy
kivy.require('1.8.0')
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.properties import ListProperty, ObjectProperty, StringProperty, NumericProperty
class Screen(TextInput):
pass
class Calculator(BoxLayout):
function_btns = ListProperty(['+', '-', '*', '/', '^', 'Mem <-', 'Mem ->', 'Clear'])
digit_btns = ListProperty(['7', '8', '9', '4', '5', '6', '1', '2', '3', '0', '.', '+/-'])
eval_string = StringProperty() # one of these strings is probably unnecessary
calc_string = StringProperty()
result = NumericProperty(0)
def build_calc(self):
# add screen textinput
self.add_widget(Screen(text='0', multiline=False, on_calc_string=self.screen_callback))
#create inner boxlayout to hold 2 button gridlayouts
main_buttons_box = BoxLayout(orientation='horizontal', size_hint=(1, 0.75))
# create 2 button gridlayouts
digit_grid = GridLayout(cols=3, rows=4, size_hint=(0.5, 1))
function_grid = GridLayout(cols=1, size_hint=(0.5, 1))
# populate grids with buttons
for i in self.digit_btns:
digit_grid.add_widget(Button(text=str(i), on_press=self.button_callback))
for f in self.function_btns:
function_grid.add_widget(Button(text=str(f), on_press=self.button_callback))
# add grids to inner boxlayout
main_buttons_box.add_widget(digit_grid)
main_buttons_box.add_widget(function_grid)
# add inner boxlayout to main grid(root)
self.add_widget(main_buttons_box)
# finally, add boxlayout at bottom of main grid and insert equals btn
equals_box = BoxLayout(size_hint=(1, 0.25))
equals_box.add_widget(Button(text='=', on_press=self.button_callback))
self.add_widget(equals_box)
def button_callback(self, instance):
value = instance.text
if value == '=':
try:
self.result = eval(self.eval_string)
self.calc_string = str(self.result)
self.eval_string = ''
except SyntaxError:
self.calc_string = 'Error: Invalid Input'
else:
self.eval_string += value
self.calc_string = self.eval_string
print self.calc_string
def screen_callback(self, instance):
instance.text = self.calc_string # not working
print 'seeing this!!!' # not working
class CalcApp(App):
def build(self):
calc = Calculator()
calc.build_calc()
return calc
if __name__ == '__main__':
CalcApp().run()
kv 文件:
#kivy: 1.0
<Screen>:
size_hint: 1, 0.25
<Calculator>:
orientation: 'vertical'
【问题讨论】:
-
仅供参考 -
Screen是标准的 Kivy 小部件,因此您应该避免在自己的小部件中使用该名称。
标签: python user-interface kivy textinput