Kivy

时间:2017-01-29 13:41:40

标签: python mobile kivy

我正在开发一个计算器,根据你花多少钱计算,你在月底会有多少钱。

我将为您提供.kv和.py。问题是,我已经完成了视觉效果,并且我已经创建了包含数学的计算器类,现在我需要将它组合成一个正常运行的GUI应用程序。

所以我想要实现的是应用程序,当你点击标有" izracunaj",计算器类(在''')中的按钮时应该接受用户输入并计算并返回结果。

main.py

import kivy
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.image import Image
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput

class Screen(GridLayout):
    def __init__(self, **kwargs):
        super(Screen, self).__init__(**kwargs)
        self.cols = 1

        self.add_widget(Label(text="Koliko imas na racunu"))
        self.stanjeNovaca = TextInput(multiline=False)
        self.add_widget(self.stanjeNovaca)

        self.add_widget(Label(text="Koliko dana do place"))
        self.stanjeDani = TextInput(multiline=False)
        self.add_widget(self.stanjeDani)

        self.add_widget(Label(text="Koliko trosis na dan"))
        self.stanjePotrosnja = TextInput(multiline=False)
        self.add_widget(self.stanjePotrosnja)

'''
class Calculator():
    def calculation():
        stanjeNovaca = input("Koliko imas para na racunu? ")
        stanjeDani = input("Koliko dana do place? ")
        stanjePotrosnja = input("koliko trosis na dan? ")
        svakiDanTrosis = stanjeDani*stanjePotrosnja
        naKrajuMjeseca = stanjeNovaca-svakiDanTrosis
        print("Ako svaki dan trosis {}, na kraju mjeseca ce ti ostati {}").format(stanjePotrosnja, naKrajuMjeseca)
        return calculation();
'''
class CalculatorApp(App):
  def build(self):
    return Screen()


CalculatorApp().run()

KV

<Screen>
    Button:
        text: "izracunaj"

2 个答案:

答案 0 :(得分:0)

我修复了你的程序。当您按下按钮时,kv文件中添加的命令会触发计算,结果将被打印。

<强> main.py

# ASCII
asciicodes = [' ','!','"','#','$','%','&','','(',')','*','+',',','-','.','/',
          '0','1','2','3','4','5','6','7','8','9',':',';','<','=','>','?','@',
          'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q',
          'r','s','t','u','v','w','x','y','z','[','\\',']','^','_']

# Braille symbols
brailles = ['⠀','⠮','⠐','⠼','⠫','⠩','⠯','⠄','⠷','⠾','⠡','⠬','⠠','⠤','⠨','⠌','⠴','⠂','⠆','⠒','⠲','⠢',
        '⠖','⠶','⠦','⠔','⠱','⠰','⠣','⠿','⠜','⠹','⠈','⠁','⠃','⠉','⠙','⠑','⠋','⠛','⠓','⠊','⠚','⠅',
        '⠇','⠍','⠝','⠕','⠏','⠟','⠗','⠎','⠞','⠥','⠧','⠺','⠭','⠽','⠵','⠪','⠳','⠻','⠘','⠸']

<强> calculator.kv

import kivy
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.image import Image
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput

class Screen(GridLayout):
    def __init__(self, **kwargs):
        super(Screen, self).__init__(**kwargs)
        self.cols = 1

        self.add_widget(Label(text="Koliko imas na racunu"))
        self.stanjeNovaca = TextInput(multiline=False)
        self.add_widget(self.stanjeNovaca)

        self.add_widget(Label(text="Koliko dana do place"))
        self.stanjeDani = TextInput(multiline=False)
        self.add_widget(self.stanjeDani)

        self.add_widget(Label(text="Koliko trosis na dan"))
        self.stanjePotrosnja = TextInput(multiline=False)
        self.add_widget(self.stanjePotrosnja)

    def calculation(self):
        svakiDanTrosis = float(self.stanjeDani.text) * float(self.stanjePotrosnja.text)
        naKrajuMjeseca = float(self.stanjeNovaca.text) - svakiDanTrosis
        print("Ako svaki dan trosis {}, na kraju mjeseca ce ti ostati {}".format(self.stanjePotrosnja.text, naKrajuMjeseca))
        return naKrajuMjeseca

class CalculatorApp(App):
  def build(self):
    return Screen()


CalculatorApp().run()

如果您想在GUI中显示结果,只需在<Screen> Button: text: "izracunaj" on_release: root.calculation() 中添加Widget(例如Label}并相应地设置其文字。

答案 1 :(得分:-2)

这个计算器在黑暗模式下看起来像 Windows 10 计算器

main.py(下)

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.core.window import Window
from kivy.lang.builder import Builder
import re

Builder.load_file('./calculator.kv')
Window.size = (350, 550)

class CalculatorWidget(Widget):
    # Clear the screen
    def clear(self):
        self.ids.input_box.text = "0"

    # Remove the last character
    def remove_last(self):
        prev_number = self.ids.input_box.text
        prev_number = prev_number[:-1]
        self.ids.input_box.text = prev_number

    # Getting the button value
    def button_value(self, number):
        prev_number = self.ids.input_box.text

        if "wrong equation" in prev_number:
            prev_number = ''

        if prev_number == '0':
            self.ids.input_box.text = ''
            self.ids.input_box.text = f"{number}"

        else:
            self.ids.input_box.text = f"{prev_number}{number}"

    # Getting the sings
    def sings(self, sing):
        prev_number = self.ids.input_box.text
        self.ids.input_box.text = f"{prev_number}{sing}"

    # Getting decimal value
    def dot(self):
        prev_number = self.ids.input_box.text
        num_list = re.split("\+|\*|-|/|%", prev_number)

        if ("+" in prev_number or "-" in prev_number or "*" in prev_number or "/" in prev_number or "%" in prev_number) and "." not in num_list[-1]:
            prev_number = f"{prev_number}."
            self.ids.input_box.text = prev_number

        elif '.' in prev_number:
            pass

        else:
            prev_number = f'{prev_number}.'
            self.ids.input_box.text = prev_number

    # Calculate the result
    def results(self):
        prev_number = self.ids.input_box.text
        try:
            result = eval(prev_number)
            self.ids.input_box.text = str(result)
        except:
            self.ids.input_box.text = "wrong equation"

    # Positive to negative
    def positive_negative(self):
        prev_number = self.ids.input_box.text
        if "-" in prev_number:
            self.ids.input_box.text = f"{prev_number.replace('-', '')}"
        else:
            self.ids.input_box.text = f"-{prev_number}"


class CalculatorApp(App):
    def build(self):
        return CalculatorWidget()

if __name__ == "__main__":
    CalculatorApp().run()

以及.kv文件中的以下代码

<Button>
    size_hint: (0.2, 0.2)
    background_normal: ""
    background_color: (0, 0, 0, 0)

<CalculatorWidget>
    BoxLayout
        orientation: "vertical"
        size: root.width, root.height

        TextInput:
            id: input_box
            text: "0"
            font_size: 43
            multiline: False
            halign: "right"
            size_hint: (1, 0.19)
            background_color: (20/255, 20/255, 30/255, 1)
            foreground_color: (1, 1, 1, 1)

        GridLayout:
            cols: 4
            rows: 5

            ### Row 1 ####
            Button:
                text: "%"
                font_size: 32
                on_press: root.sings("%")
                background_color: (14/255, 73/255, 176/255, 1)

            Button:
                text: "C"
                font_size: 32
                on_press: root.clear()
                background_color: (14/255, 73/255, 176/255, 1)

            Button:
                text: u"\u00AB"
                font_size: 32
                on_press: root.remove_last()
                background_color: (14/255, 73/255, 176/255, 1)

            Button:
                text: "/"
                font_size: 32
                background_color: (14/255, 73/255, 176/255, 1)
                on_press: root.sings("/")
                background_color: (14/255, 73/255, 176/255, 1)

            #### Row 2 #####
            Button:
                text: "7"
                font_size: 32
                on_press: root.button_value(7)

            Button:
                text: "8"
                font_size: 32
                on_press: root.button_value(8)

            Button:
                text: "9"
                font_size: 32
                on_press: root.button_value(9)

            Button:
                text: "x"
                font_size: 32
                background_color: (14/255, 73/255, 176/255, 1)
                on_press: root.sings("*")

            #### Row 3 ###
            Button:
                text: "4"
                font_size: 32
                on_press: root.button_value(4)

            Button:
                text: "5"
                font_size: 32
                on_press: root.button_value(5)

            Button:
                text: "6"
                font_size: 32
                on_press: root.button_value(6)

            Button:
                text: "-"
                font_size: 32
                background_color: (14/255, 73/255, 176/255, 1)
                on_press: root.sings("-")

            ### Row 4 ###
            Button:
                text: "1"
                font_size: 32
                on_press: root.button_value(1)

            Button:
                text: "2"
                font_size: 32
                on_press: root.button_value(2)

            Button:
                text: "3"
                font_size: 32
                on_press: root.button_value(3)

            Button:
                text: "+"
                font_size: 32
                background_color: (14/255, 73/255, 176/255, 1)
                on_press: root.sings("+")

            ### Row 5 ###
            Button:
                text: "+/-"
                font_size: 32
                on_press: root.positive_negative()

            Button:
                text: "0"
                font_size: 32
                on_press: root.button_value(0)

            Button:
                text: "."
                font_size: 32
                on_press: root.dot()

            Button:
                text: "="
                font_size: 32
                background_color: (14/255, 73/255, 176/255, 1)
                on_press: root.results()