来自tkinter代码的Python flask Web计算器项目端口

问题描述

我为哥哥经营一个项目,他的哥哥拥有一家木工店,并具有使用tkinter和python构建的功能计算器,但希望使用基于Web的应用程序以提高灵活性/便携性。

原始代码

from tkinter import *

window = Tk()
window.title("BFCalc")
window.geometry("525x800")
window.resizable(width=False,height=False)
E1Val = StringVar()
E1_value = StringVar()
E2_value = StringVar()
E3_value = StringVar()

answers = []

def CalculateNum(event):
    LengthVal = float(E1_value.get())
    WidthVal = float(E2_value.get())
    ThicknessVal = float(E3_value.get())

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

    E4.delete(0,"end")
    E4.insert(END,FinalCalc)
    T1.insert(END,f'{FinalCalc}\n')
    Total()
    TotalBoards()

def Total():
    tot = 0
    for num in answers:
        tot += num
   
    E5.delete(0,"end")
    E5.insert(END,round(tot,2))

def ClearVal():
    E1.delete(0,"end")
    E2.delete(0,"end")
    E3.delete(0,"end")
    E4.delete(0,"end")
    E3.insert(0,'1')

def TotalBoards():
    E6.delete(0,"end")
    E6.insert(END,len(answers))

def ClearList():
    T1.delete('1.0',END)
    E5.delete(0,"end")
    E6.delete(0,"end")
    answers.clear()

L1 = Label(text="Board Foot Calculator",font='Helvetica 20 bold underline')
L1.pack()

L2 = Label(text="Input in Inches",font='Helvetica 16 bold underline')
L2.pack(pady=10)

L3 = Label(text="Length",font='Helvetica 14 bold italic')
L3.pack()

E1 = Entry(window,font='Goudy 14 bold',textvariable=E1_value)
E1.pack()

L4 = Label(text="Width",font='Helvetica 14 bold italic')
L4.pack()

E2 = Entry(window,textvariable=E2_value)
E2.pack()

L5 = Label(text="Thickness",font='Helvetica 14 bold italic')
L5.pack()

E3 = Entry(window,textvariable=E3_value)
E3.insert(0,'1')
E3.pack()

B1 = Button(window,text="Calculate",font='Helvetica 14 bold',height=2,width=15)
B1.bind("<Button-1>",CalculateNum)
B1.bind("<KeyPress-Return>",CalculateNum)
B1.pack(pady=40)

L6 = Label(text="Board Feet",font='Helvetica 16 bold italic')
L6.pack()

E4 = Entry(window,font='Goudy 14 bold')
E4.pack()

B2 = Button(window,text="Clear",width=10,command=ClearVal)
B2.pack(pady=40)

B3 = Button(window,text="Clear List",command=ClearList)
B3.pack()

L9 = Label(text="Total Boards:",font='Goudy 14 bold')
L9.place(x=50,y=740)

E6 = Entry(window,font='Goudy 16 bold')
E6.place(x=250,y=740)

L7 = Label(text="Coded by Lucio (C) 2020",font='Goudy 12')
L7.pack()

T1 = Text(window,height=34,font='Goudy 12')
T1.place(x=400,y=50)

E5 = Entry(window,font='Goudy 16 bold')
E5.place(x=250,y=700)

L8 = Label(text="Total Board Feet:",font='Goudy 14 bold')
L8.place(x=50,y=700)

window.mainloop()

到目前为止,我已经创建了以下代码,但遇到两个错误:“方法没有参数”第16行和“可重用形式的实例没有'errors'成员第19行

from flask import Flask,redirect,url_for,request,render_template,flash
from wtforms import Form,StringField,SubmitField,FloatField,validators
from flask_wtf import FlaskForm

DEBUG = True
app = Flask(__name__)
app.config.from_object(__name__)
app.config['SECRET KEY'] = '7045-Fosforo-85718-TucsonAZ'

class ReusableForm(Form):
    LengthVal = FloatField('Length:',validators=[validators.required()])
    WidthVal = FloatField('Width:',validators=[validators.required()])
    ThickVal = FloatField('Thickness:',validators=[validators.required()])

    @app.route('/',methods = ['POST','GET'])
    def CalculateNum():
        form = ReusableForm(request.form)

        print (form.errors)
        if request.method == 'POST':
            LengthVal = request.form['LengthVal']
            WidthVal = request.form['WidthVal']
            ThickVal = request.form['ThickVal']
            print (LengthVal," ",WidthVal,ThickVal)

        if form.validate():
            FinalCalc = LengthVal * WidthVal * ThickVal / 144
            FinalCalc = round(FinalCalc,2)
            flash('Total Board Feet: ' + FinalCalc)
     
        else:
            flash('Error: All form fields required')

        return render_template('boards.html')

if __name__ == '__main__':
    app.run(debug= True,port=5000)

和html模板:

<html>
<head>
<!-- required Meta tags -->
<Meta charset="utf-8">
<Meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">

<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Tucson Woodcraft Board Feet Calculator</title>
</head>
<body>
<div class="container"> 
    <h1>Board Foot Calculator</h1>
    <form action="" method="POST" role="form"
        { { form.csrf } }
    <div class="form-group">
        <label for="LengthVal">Length:</label>
        <input type="float" class="form-control" id="LengthVal" placeholder="Enter in inches"><br>
        <label for="WidthVal">Width:</label>
        <input type="float" class="form-control" id="WidthVal" placeholder="Enter in inches"><br>
        <label for="ThickVal">Thickness:</label>
        <input type="float" class="form-control" id="ThickVal" placeholder="Enter in inches"><br></div>
        <button type="submit" class="btn btn-success">Calculate</button>
    </form>{% with messages = get_flashed_messages(with_categories=true) %}
    {% if messages %}

    {% for message in messages %}
    {% if "Error" not in message [1]: %}
    <div class="alert alert-info">
        <strong>Success!</strong> { { message [1] }}
    </div>
    
    {% endif %}

    {% if "Error" in message[1]: %}
    <div class="alert alert-warning">
                { { message[1] }}</div>
    {% endif %}
    {% endfor %}
    {% endif %}
    {% endwith %}


    </div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>      
</body>
</html>

我是一个非常初学者,正尝试自己学习python,但是努力奋斗,但是我很想为我的兄弟解决这个问题。

感谢您提供的任何帮助!

解决方法

您需要至少在类内部的函数中添加“ self”参数。另外,如果要调用form.errors,则需要定义一个“错误”函数,如下所示。

from flask import Flask,redirect,url_for,request,render_template,flash
from wtforms import Form,StringField,SubmitField,FloatField,validators
from flask_wtf import FlaskForm

DEBUG = True
app = Flask(__name__)
app.config.from_object(__name__)
app.config['SECRET KEY'] = '7045-Fosforo-85718-TucsonAZ'

class ReusableForm(Form):
    def __init__(self):
        pass
    
    LengthVal = FloatField('Length:',validators=[validators.required()])
    WidthVal = FloatField('Width:',validators=[validators.required()])
    ThickVal = FloatField('Thickness:',validators=[validators.required()])

    @app.route('/',methods = ['POST','GET'])

    def errors(self):
        return "these are some errors"

    def CalculateNum(self):
        form = ReusableForm(request.form)

        print (form.errors)
        if request.method == 'POST':
            LengthVal = request.form['LengthVal']
            WidthVal = request.form['WidthVal']
            ThickVal = request.form['ThickVal']
            print (LengthVal," ",WidthVal,ThickVal)

        if form.validate():
            FinalCalc = LengthVal * WidthVal * ThickVal / 144
            FinalCalc = round(FinalCalc,2)
            flash('Total Board Feet: ' + FinalCalc)
     
        else:
            flash('Error: All form fields required')

        return render_template('boards.html')

if __name__ == '__main__':
    app.run(debug= True,port=5000)