python的pywebview框架使用记录

pywebview是python的一个库,类似于flask框架,这也是用来构建网页的软件包,它的特点就是不用更多的和html语言和js语言,更多的使用python语言就可以完成网页的创建和元素的监听该库的简介和示例,简单使用看示例足够,但是其中也不够详尽:https://pywebview.flowrl.com/

一、安装pywebview

首先,确保已经安装了pywebview可以通过以下命令进行安装:

pip install pywebview

 二、简单使用

简单的创建界面和一些基础操作,这里不再赘述,也没什么营养,官方示例都已给出,这里只贴上一些示例:

一个示例界面;

import webview

if __name__ == '__main__':
    # Create a standard webview window
    window = webview.create_window('Simple browser', 'https://pywebview.flowrl.com/hello')
    webview.start()

一个自制界面:

import webview

html = """
  <html>
    <head></head>
    <body>
      <h2>Links</h2>

      <p><a href='https://pywebview.flowrl.com'>Regular links</a> are opened in the application window.</p>
      <p><a href='https://pywebview.flowrl.com' target='_blank'>target='_blank' links</a> are opened in an external browser.</p>

    </body>
  </html>
"""

if __name__ == '__main__':
    window = webview.create_window('Link types', html=html)
    webview.start()

调用的是外部界面:

import webview


if __name__ == '__main__':
    window = webview.create_window(title='Webview App', url="https://hailuoai.com/?type=chat&chatID=251739240281759747/", confirm_close=True,
                                   zoomable=True, vibrancy=True, width=1275, height=745)
    webview.start(user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0',
                  debug=True)

 于是可以从这几个例子看出来,pywebview主要有两种,可以是自制的网页html参数,又或者是url的外部链接。

三、高级使用

主要是关于dom的元素创建选择何使用:按钮等等,关于bind函数

import random
import webview

rectangles = []

def random_color():
    red = random.randint(0, 255)
    green = random.randint(0, 255)
    blue = random.randint(0, 255)

    return f'rgb({red}, {green}, {blue})'

def bind(window):
    def toggle_disabled():
        disabled = None if len(rectangles) > 0 else True
        remove_button.attributes = { 'disabled': disabled }
        empty_button.attributes = { 'disabled': disabled }
        move_button.attributes = { 'disabled': disabled }

    def create_rectangle(_):
        color = random_color()
        rectangle = window.dom.create_element(f'<div class="rectangle" style="background-color: {color};"></div>', rectangle_container)
        rectangles.append(rectangle)
        toggle_disabled()

    def remove_rectangle(_):
        if len(rectangles) > 0:
            rectangles.pop().remove()
        toggle_disabled()

    def move_rectangle(_):
        if len(rectangle_container.children) > 0:
            rectangle_container.children[-1].move(circle_container)

    def empty_container(_):
        rectangle_container.empty()
        rectangles.clear()
        toggle_disabled()

    def change_color(_):
        circle.style['background-color'] = random_color()

    def toggle_class(_):
        circle.classes.toggle('circle')

    rectangle_container = window.dom.get_element('#rectangles')
    circle_container = window.dom.get_element('#circles')
    circle = window.dom.get_element('#circle')

    toggle_button = window.dom.get_element('#toggle-button')
    toggle_class_button = window.dom.get_element('#toggle-class-button')
    duplicate_button = window.dom.get_element('#duplicate-button')
    remove_button = window.dom.get_element('#remove-button')
    move_button = window.dom.get_element('#move-button')
    empty_button = window.dom.get_element('#empty-button')
    add_button = window.dom.get_element('#add-button')
    color_button = window.dom.get_element('#color-button')

    toggle_button.events.click += lambda e: circle.toggle()
    duplicate_button.events.click += lambda e: circle.copy()
    toggle_class_button.events.click += toggle_class
    remove_button.events.click += remove_rectangle
    move_button.events.click += move_rectangle
    empty_button.events.click += empty_container
    add_button.events.click += create_rectangle
    color_button.events.click += change_color

if __name__ == '__main__':
    window = webview.create_window(
        'DOM Manipulations Example', html='''
            <html>
                <head>
                <style>
                    button {
                        font-size: 100%;
                        padding: 0.5rem;
                        margin: 0.3rem;
                        text-transform: uppercase;
                    }

                    .rectangle {
                        width: 100px;
                        height: 100px;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        margin: 0.5rem;
                        border-radius: 5px;
                        background-color: red;
                    }

                    .circle {
                        border-radius: 50px;
                        background-color: red;
                    }

                    .circle:hover {
                        background-color: green;
                    }

                    .container {
                        display: flex;
                        flex-wrap: wrap;
                    }
                </style>
                </head>
                <body>
                    <button id="toggle-button">Toggle circle</button>
                    <button id="toggle-class-button">Toggle class</button>
                    <button id="color-button">Change color</button>
                    <button id="duplicate-button">Duplicate circle</button>
                    <button id="add-button">Add rectangle</button>
                    <button id="remove-button" disabled>Remove rectangle</button>
                    <button id="move-button" disabled>Move rectangle</button>
                    <button id="empty-button" disabled>Remove all</button>
                    <div id="circles" style="display: flex; flex-wrap: wrap;">
                        <div id="circle" class="rectangle circle"></div>
                    </div>

                    <div id="rectangles" class="container"></div>
                </body>
            </html>
        '''
    )
    webview.start(bind, window)

并且使用event可以监听按钮等等的事件发生

并且是支持动态生成元素的:

with open(file_path, 'r', encoding='utf-8') as file:
    for line in file:
        count += 1
        window.dom.create_element(
            f"<input id='word{count}' writingsuggestions='true' type='text' class='editable-textbox'>111</input>"
        )
        temp = window.dom.get_element(f'#word{count}')
        line = line.rstrip('\n')
        temp.value = line

希望可以帮助到大家!! 

 

很抱歉,作为AI语言模型,我不能实际编写代码。但我可以给你提供一个使用pywebview编写桌面登录的示例代码,你可以根据它进行修改和完善。 ```python import webview def login(username, password): # 进行登录操作 # 如果登录成功,返回True # 如果登录失败,返回False return True def on_submit(data): username = data['username'] password = data['password'] if login(username, password): webview.windows[0].evaluate_js('alert("登录成功!")') else: webview.windows[0].evaluate_js('alert("登录失败,请检查用户名和密码。")') if __name__ == '__main__': html = """ <html> <body> <form onsubmit="onSubmit(); return false;"> <label for="username">用户名:</label> <input type="text" id="username" name="username"><br><br> <label for="password">密码:</label> <input type="password" id="password" name="password"><br><br> <input type="submit" value="登录"> </form> <script> function onSubmit() { var username = document.getElementById('username').value; var password = document.getElementById('password').value; window.pywebview.api.on_submit({username: username, password: password}); } </script> </body> </html> """ webview.create_window("登录", html=html, js_api={ 'on_submit': on_submit, }) ``` 这个示例代码创建了一个简单的登录窗口,并使用js_api向Python代码传递表单数据。在Python代码中,我们通过login函数进行登录操作,如果登录成功则弹出提示框,否则也弹出一个提示框。你可以根据自己的需求进行修改和完善。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

monster justin

感谢您的打赏,更新的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值