按下按钮后在Kivy应用程序中运行Flask应用程序

2024-09-28 23:09:19 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种方法可以让我在Kivy应用程序中同时运行Kivy和Flask?此外,我需要这个应用程序,所以一旦你点击Kivy应用程序中的一个按钮,就会触发一个启动Flask网页的功能。然后,使用Python内置的webbrowser模块,我需要它在默认浏览器中自动打开网页

当运行此代码时,我没有得到任何错误。只是Kivy应用程序冻结,不再响应

到目前为止,我的代码是:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from flask import Flask
from werkzeug.serving import run_simple
import webbrowser

Builder.load_file('design.kv')

answers = []

class CalcScreen(Screen):
    def list_view(self):
        self.manager.current = "list_screen"
    def cround_view(self):
        self.manager.current = "round_calc_screen"
    def calculate(self):
        LengthVal = float(self.ids.length.text)
        WidthVal = float(self.ids.width.text)
        ThicknessVal = float(self.ids.thickness.text)

        FinalCalc = LengthVal * WidthVal * ThicknessVal / 144
        FinalCalc = round(FinalCalc,1)
        answers.append(FinalCalc)

        self.ids.board_feet.text = str(FinalCalc)

class ListScreen(Screen):
    def calc_view(self):
        self.manager.current = "calc_screen"
    def UpdateInfo(self):
        tot = 0
        for num in answers:
            tot += num

        self.ids.total_board_feet.text = str(round(tot,1))
        self.ids.total_boards.text = str(len(answers))
        self.ids.list.text = str(', '.join(map(str, answers)))
    def ClearListAnswers(self):
        answers.clear()
    def printerview(self):
        app = Flask(__name__)

        @app.route('/')
        def home():
            return f"<h1>BFCalc Printer Friendly View</h1>\n{self.ids.list.text}"

        run_simple('localhost',5000,app)

        webbrowser.open_new('localhost:5000')

class RoundCalcScreen(Screen):
    def calc_view(self):
        self.manager.current = "calc_screen"
    def rc_calculate(self):
        RC_DiameterVal = float(self.ids.rc_diameter.text)
        RC_RadiusVal = RC_DiameterVal / 2
        RC_ThicknessVal = float(self.ids.rc_thickness.text)

        RC_FinalCalc = (3.14 * (RC_RadiusVal * RC_RadiusVal) * RC_ThicknessVal) / 144
        RC_FinalCalc = round(RC_FinalCalc,1)
        answers.append(RC_FinalCalc)

        self.ids.rc_board_feet.text = str(RC_FinalCalc)

class RootWidget(ScreenManager):
    pass

class MainApp(App):
    def build(self):
        self.icon = 'icon.ico'
        return RootWidget()

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

Tags: textfromimportself应用程序idsdefcalc
1条回答
网友
1楼 · 发布于 2024-09-28 23:09:19

以这种方式使用后端框架是一种不好的做法(它们根本没有以这种方式使用)。这取决于您的需要,您可以尝试使用纯HTML

def printerview(self):
    import webbrowser

    file_name = "my_html.html"
    html = f"""<h1>BFCalc Printer Friendly View</h1>\n{self.ids.list.text}"""
    with open(file_name, "w+") as f:
        f.write(html)
    # open html in a browser
    webbrowser.open(file_name)

相关问题 更多 >