编程语言
首页 > 编程语言> > 用python做个计算器不是轻轻松松吗~

用python做个计算器不是轻轻松松吗~

作者:互联网

计算器

Kivy是一个免费的开源Python库,可以快速轻松地开发高度交互的跨平台应用程序。

这里我将使用Python中的Kivy包来构建一个计算器GUI。
(https://jq.qq.com/?_wv=1027&k=8PRAY8Vo)

python答疑 咨询 学习交流群2:660193417###
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label


class myApp(App):
    def build(self):
        root_widget = BoxLayout(orientation='vertical')
        output_label = Label(size_hint_y=0.75, font_size=50)
        button_symbols = ('1', '2', '3', '+',
                          '4', '5', '6', '-',
                          '7', '8', '9', '.',
                          '0', '*', '/', '=')
        button_grid = GridLayout(cols=4, size_hint_y=2)
        for symbol in button_symbols:
            button_grid.add_widget(Button(text=symbol))

        clear_button = Button(text='Clear', size_hint_y=None, height=100)
        def print_button_text(instance):
            output_label.text += instance.text
        for button in button_grid.children[1:]:
            button.bind(on_press=print_button_text)
        def resize_label_text(label, new_height):
            label.fontsize = 0.5*label.height
        output_label.bind(height=resize_label_text)

        def evaluate_result(instance):
            try:
                output_label.text = str(eval(output_label.text))
            except SyntaxError:
                output_label.text = 'Python Syntax error!'
        button_grid.children[0].bind(on_press=evaluate_result)

        def clear_label(instance):
            output_label.text = " "
        clear_button.bind(on_press=clear_label)

        root_widget.add_widget(output_label)
        root_widget.add_widget(button_grid)
        root_widget.add_widget(clear_button)
        return root_widget


myApp().run()
python答疑 咨询 学习交流群2:660193417###

运行代码,出现一个计算器,非常好用!

请添加图片描述

标签:widget,python,text,button,label,grid,计算器,output,轻轻松松
来源: https://www.cnblogs.com/xiaoxiongmao123/p/16383817.html