Beeware使用python开发安卓应用

briefcase dev 调试
briefcase create android 创建
briefcase build android 构造

可以将第三方的包的镜像链接放进pyproject.toml中的:

requires = [
'https://mirrors.aliyun.com/pypi/packages/02/55/67a3c17b9e7d972ed8c246f104da99ca4f3ea42fba566697e479011b84b6/Pillow-9.2.0-cp310-cp310-win_amd64.whl#sha256=254164c57bab4b459f14c64e93df11eff5ded575192c294a0c49270f22c5d93d',
    'https://mirrors.aliyun.com/pypi/packages/42/87/4a3a77e59ab7493d64da1f69bf1c2e899a4cf81e51b2baa855e8cc8115be/qrcode-6.1-py2.py3-none-any.whl#sha256=3996ee560fc39532910603704c82980ff6d4d5d629f9c3f25f34174ce8606cf5',
]

整体界面的关键是Toga的使用 官方Toga教程

展示图片,定义 图片控件的添加

图片保存的话直接保存到了别的地方,使用下面的代码配合一个个加回来

cur_path = os.path.abspath(os.path.dirname(__file__))

第三方库的使用还是有点问题,通过上面的方法可以编译,但是运行的时候会报错!

所以尽量尝试使用原生的库

import urllib.request as request
url = 'https://tool.oschina.net/action/qrcode/generate?data={}&output=image%2Fjpeg'.format('ij')
image = request.urlretrieve(url, 'image.jpg')

上面这段生成二维码的代码耗时0.6秒,不错了

Toga学习

基本的原理,下面的代码将创建一个带按钮的窗口,点击按钮会在控制台打印hello

# -*- coding: utf-8 -*-
# @Time : 2022/9/26 21:25
# @Author : Lanpangzi
# @File : study.py
#  此教程的网页:https://toga.readthedocs.io/en/latest/tutorial/tutorial-0.html

import toga


def button_handler(widget):
    print("hello")


def build(app):
    # Box是一个城防小部件的容器
    box = toga.Box()
    button = toga.Button('Hello world', on_press=button_handler)
    # toga使用的是类似于css的样式设计模式
    #    padding指的是与四周边的距离
    button.style.padding = 20
    # flex控制的是与左右控件的关系
    button.style.flex = 1
    box.add(button)
    return box


def main():
    # 最终调用的是这个main函数,build函数只是他的一个参数
    return toga.App('First App', 'org.beeware.helloworld', startup=build)


if __name__ == '__main__':
    main().main_loop()

下面的是创建一个温度转换器

# -*- coding: utf-8 -*-
# @Time : 2022/9/26 22:23
# @Author : Lanpangzi
# @File : study2.py
import toga
from toga.style.pack import COLUMN, LEFT, RIGHT, ROW, Pack


def build(app):
    # box里面可以塞box
    c_box = toga.Box()
    f_box = toga.Box()
    box = toga.Box()
    
    c_input = toga.TextInput(readonly=True)
    f_input = toga.TextInput()

    c_label = toga.Label('Celsius', style=Pack(text_align=LEFT))
    f_label = toga.Label('Fahrenheit', style=Pack(text_align=LEFT))
    join_label = toga.Label('is equivalent to', style=Pack(text_align=RIGHT))

    def calculate(widget):
        try:
            c_input.value = (float(f_input.value) - 32.0) * 5.0 / 9.0
        except ValueError:
            c_input.value = '???'
    
    button = toga.Button('Calculate', on_press=calculate)
    
    # 可以先把所有的组件都塞进去,然后再update布局
    f_box.add(f_input)
    f_box.add(f_label)

    c_box.add(join_label)
    c_box.add(c_input)
    c_box.add(c_label)

    box.add(f_box)
    box.add(c_box)
    box.add(button)

    # 没有下面的update程序也能正常运行,但是布局就是默认的了
    box.style.update(direction=COLUMN, padding_top=10)
    f_box.style.update(direction=ROW, padding=5)
    c_box.style.update(direction=ROW, padding=5)

    c_input.style.update(flex=1)
    f_input.style.update(flex=1, padding_left=160)
    c_label.style.update(width=100, padding_left=10)
    f_label.style.update(width=100, padding_left=10)
    join_label.style.update(width=150, padding_right=10)

    button.style.update(padding=15, flex=1)

    return box


def main():
    return toga.App('Temperature Converter', 'org.beeware.f_to_c', startup=build)


if __name__ == '__main__':
    main().main_loop()

创建一个自己的浏览器,这玩意需要一个edge的小玩意,不知道安卓能不能运行。。。。

# -*- coding: utf-8 -*-
# @Time : 2022/9/26 23:10
# @Author : Lanpangzi
# @File : 创建浏览器窗口.py

import toga
from toga.style.pack import CENTER, COLUMN, ROW, Pack


class Graze(toga.App):
    def startup(self):
        self.main_window = toga.MainWindow(title=self.name)
        #  on_webview_load是当按钮按下时调用的函数,哪来的按钮??应该是网页中的按钮
        # 先定义所有的组件,然后再组装起来
        self.webview = toga.WebView(on_webview_load=self.on_webview_loaded, style=Pack(flex=1))
        self.url_input = toga.TextInput(
            value='https://beeware.org/',
            style=Pack(flex=1)
        )
      
        self.button = toga.Button('Go', on_press=self.load_page, style=Pack(width=50, padding_left=5))
        self.up_box = toga.Box()
        self.up_box.add(self.url_input, self.button)
        self.main_box = toga.Box(style=Pack(direction=COLUMN))
        self.main_box.add(self.up_box, self.webview)

        self.main_window.content = self.main_box
        self.webview.url = self.url_input.value

        # Show the main window
        self.main_window.show()

    def load_page(self, widget):
        self.webview.url = self.url_input.value

    def on_webview_loaded(self, widget):
        self.url_input.value = self.webview.url


def main():
    return Graze('Graze', 'org.beeware.graze')


if __name__ == '__main__':
    main().main_loop()

返校码制作方案2,直接爬取并保存图片,这个方案的二维码没有颜色

# -*- coding: utf-8 -*-
# @Time : 2022/9/26 23:39
# @Author : Lanpangzi
# @File : 爬取并显示图片.py

# -*- coding: utf-8 -*-
# @Time : 2022/9/26 23:39
# @Author : Lanpangzi
# @File : 爬取并显示图片.py

import urllib.request as request
import urllib.parse as parse
import toga
from toga.style.pack import CENTER, COLUMN, ROW, Pack
import os
import time


class ShowImage(toga.App):
    def startup(self):
        self.image_id = 0
        self.user_id = 0
        self.main_window = toga.MainWindow(title=self.name)
        # 先定义所有的组件,然后再组装起来
        self.id_input = toga.TextInput(
            value='请复制微信扫描返校码后生成的文字并粘贴到此处',
            # value='sa_sas_a',
            style=Pack(flex=1)
        )
        self.button = toga.Button('生成返校码', on_press=self.get_image, style=Pack(flex=1))
        self.up_box = toga.Box(style=Pack(direction=COLUMN))
        self.up_box.add(self.id_input, self.button)
        self.main_box = toga.Box(style=Pack(direction=COLUMN))
        self.image_window = toga.ImageView(toga.Image(path='1.png'))
        self.main_box.add(self.up_box, self.image_window)
        self.main_window.content = self.main_box

        # Show the main window
        self.main_window.show()

    def get_image(self, widget):
        time_stamp = self.get_time_stamp()
        if self.user_id == 0:
            self.user_id = self.id_input.value.split('_')[0] + '_' + self.id_input.value.split('_')[1]
        id = parse.quote(self.user_id + '_' + time_stamp)
        print(id)
        start_time = time.perf_counter()
        cur_path = os.path.abspath(os.path.dirname(__file__))
        url = 'https://tool.oschina.net/action/qrcode/generate?data={}&output=image%2Fjpeg'.format(id)
        path_a_name = os.path.join(cur_path, 'image_{}.jpg'.format(self.image_id))
        request.urlretrieve(url, path_a_name)
        end_time = time.perf_counter()
        print('图片已生成,耗时:{}'.format(end_time - start_time))
        self.change_window()

    def change_window(self):
        # self.main_window = toga.MainWindow(title=self.name)
        self.top_image = toga.ImageView(toga.Image(path='top_img.png'),
                                        style=Pack(height=200, flex=1))
        self.top_box = toga.Box(style=Pack(flex=1))
        self.top_box.add(self.top_image)

        self.button = toga.Button('刷新校园码', on_press=self.get_image,
                                  style=Pack(width=105, padding_top=10, color="#16c010"))
        # self.up_box = toga.Box(style=Pack(flex=1))
        # self.up_box.add(self.button)

        cur_path = os.path.abspath(os.path.dirname(__file__))
        path_a_name = os.path.join(cur_path, 'image_{}.jpg'.format(self.image_id))
        self.image_id += 1
        self.image_window = toga.ImageView(toga.Image(path=path_a_name), style=Pack(height=200, color='#16c010'))
        self.image_box = toga.Box(style=Pack(alignment='center', direction=COLUMN))
        self.image_box.add(self.image_window, self.button)

        self.main_box = toga.Box(style=Pack(direction=COLUMN))
        self.main_box.add(self.top_box, self.image_box)
        self.main_window.content = self.main_box
        # self.main_window.show()

    def get_time_stamp(self):
        return str(time.time())[:10]


def main():
    return ShowImage('返校码快速打开', 'org.beeware.graze')


if __name__ == '__main__':
    main().main_loop()



不能挂着梯子使用,会非常慢!!

要想所有的元素都居中排布,需要设置main_box

self.main_box = toga.Box(style=Pack(direction=COLUMN, alignment=CENTER))

使用页面内浏览器实现带颜色的二维码,但是比例还是有点问题无法调整

# -*- coding: utf-8 -*-
# @Time : 2022/9/26 23:39
# @Author : Lanpangzi
# @File : 爬取并显示图片.py

import toga
from toga.style.pack import CENTER, COLUMN, Pack
import time
import os


class ShowImage(toga.App):
    def startup(self):
        self.user_id = 0
        self.main_window = toga.MainWindow(title=self.name)
        self.cur_path = os.path.abspath(os.path.dirname(__file__))
        input_value = '请复制微信扫描返校码后生成的文字并粘贴到此处'
        if os.path.exists(os.path.join(self.cur_path, 'user_id.txt')):
            with open(os.path.join(self.cur_path, 'user_id.txt'), 'r') as fp:
                input_value = fp.readline()
        self.id_input = toga.TextInput(
            value=input_value,
            style=Pack(flex=1)
        )
        self.button = toga.Button('生成返校码', on_press=self.get_image, style=Pack(flex=1))
        self.main_box = toga.Box(style=Pack(direction=COLUMN))
        self.main_box.add(self.id_input, self.button)
        self.main_window.content = self.main_box
        self.main_window.show()

    def get_image(self, widget):
        self.top_image = toga.ImageView(toga.Image(path='top_img.png'),
                                        style=Pack(height=200, flex=1))
        self.button = toga.Button('刷新校园码', on_press=self.change_window,
                                  style=Pack(width=105, padding_top=10, color="#16c010"))
        self.webview = toga.WebView(style=Pack(width=250, height=250, padding_top=20))
        self.change_window(widget=widget)
        self.webbox = toga.Box(style=Pack(direction=COLUMN))
        self.webbox.add(self.webview)
        self.main_box = toga.Box(style=Pack(direction=COLUMN, alignment=CENTER))
        self.main_box.add(self.top_image, self.webbox, self.button)
        self.main_window.content = self.main_box
        self.main_window.show()

    def change_window(self, widget):
        if self.user_id == 0:

            self.user_id = self.id_input.value.split('_')[0] + '_' + self.id_input.value.split('_')[1]

        id = self.user_id + '_' + self.get_time_stamp()
        with open(os.path.join(self.cur_path, 'user_id.txt'), 'w') as fp:
            fp.write(id)

        self.webview.url = 'https://tool.lu/qrcode/basic.html?text={}&tolerance=15&size=250&margin=0&front_color=%2327a844&background_color=%23ffffff'.format(
            id)

    def get_time_stamp(self):
        return str(time.time())[:10]


def main():
    return ShowImage('返校码快速打开', 'org.beeware.graze')


if __name__ == '__main__':
    main().main_loop()

你可能感兴趣的:(日常练习,android,python,开发语言)