編程類項目。我一直收到同樣的錯誤

維多利亞·桑切斯-阿佩拉尼茲

我是 python 的新手,我正在嘗試在 Gui Python 中創建一個應用程序。目標是創建一個註冊/註冊頁面。然後,應該向用戶開放四種可能性

  • 催乳器
  • 文件寫入
  • BMI計算器
  • 出口

該代碼運行良好,直到我嘗試添加帶有註冊或註冊按鈕的第一頁。現在我一直收到這個錯誤:“位置參數跟隨關鍵字參數”但是,我找不到錯誤在哪裡。如果有人能幫助我,我將不勝感激!!!

from tkinter import *
from tkinter import messagebox
import functions




class App(Tk):
    def __init__(self):
        Tk.__init__(self)
        self._frame = None
        self.title("Healtheat")
        self.switch(Entering)
        self.geometry('350x350')
        self.config(bg = "black")

    def switch(self, frame_class):
        """Destroys current frame and replaces it with a chosen by the user"""
        new_frame = frame_class(self)
        if self._frame is not None:
            self._frame.destroy()
        self._frame = new_frame
        self._frame.pack()

class Entering(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        self.config(bg = "black")

        global main_screen
        main_screen.title("Heyyy :)")
        Label(text="Select Your Choice", bg="lightseagreen", width="300", height="2", font=("Calibri", 13)).pack()
        Label(text="").pack()
        Button(text="Login", height="2", width="30", command = lambda: master.switch(Login)).pack()
        Label(text="").pack()
        Button(text="Register", height="2", width="30", command = lambda: master.switch(Register)).pack()


class Register(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        self.config(bg = "black")

    def register():
        global register_screen
        register_screen = Toplevel(main_screen)
        register_screen.title("Join us our team")
        register_screen.geometry("350x350")

        global username
        global password
        global img
        global username_entry
        global password_entry

        username = StringVar()
        password = StringVar()


        Label(register_screen, text="Please enter details below", bg="red").pack()
        Label(register_screen, text="").pack()

        username_lable = Label(register_screen, text="Username * ")
        username_lable.pack()
        username_entry = Entry(register_screen, textvariable=username)
        username_entry.pack()

        password_lable = Label(register_screen, text="Password * ")
        password_lable.pack()
        password_entry = Entry(register_screen, textvariable=password, show='*')
        password_entry.pack()

        Label(register_screen, text="").pack()
        Button(register_screen, text="Register", width=10, height=1, bg="lightseagreen", lambda: master.switch(Login)).pack()

class Login(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        self.config(bg = "black")

    def login(self):
        global login
        login_screen = Toplevel(main_screen)
        login_screen.title("Welcome back!")
        login_screen.geometry("350x350")
        Label(login_screen, text="Please enter details below to login").pack()
        Label(login_screen, text="").pack()

        global username_verify
        global password_verify

        self.username_verify = StringVar()
        self.password_verify = StringVar()

        global username_login_entry
        global password_login_entry

        Label(login_screen, text="Username * ").pack()
        username_login_entry = Entry(login_screen, textvariable=username_verify)
        username_login_entry.pack()
        Label(login_screen, text="").pack()
        Label(login_screen, text="Password * ").pack()
        password_login_entry = Entry(login_screen, textvariable=password_verify, show='*')
        password_login_entry.pack()
        Label(login_screen, text="").pack()
        Button(login_screen, text="Login", width=10, height=1, command=login_verify).pack()

    def login_verify(self):
        self.username1 = username_verify.get()
        self.password1 = password_verify.get()
        username_login_entry.delete(0, END)
        password_login_entry.delete(0, END)

        list_of_files = os.listdir()
        if username1 in list_of_files:
            file1 = open(username1, "r")
            verify = file1.read().splitlines()
            if password1 in verify:
                login_sucess()

            else:
                password_not_recognised()

        else:
            user_not_found()

    def login_sucess(self):
        global login_success_screen
        login_success_screen = Toplevel(login_screen)
        login_success_screen.title("Success")
        login_success_screen.geometry("150x100")
        Label(login_success_screen, text="Login Success").pack()
        Button(login_success_screen, text="OK", lambda: master.switch(Menu)).pack()

    def password_not_recognised(self):
        global password_not_recog_screen
        password_not_recog_screen = Toplevel(login_screen)
        password_not_recog_screen.title("Success")
        password_not_recog_screen.geometry("150x100")
        Label(password_not_recog_screen, text="Invalid Password ").pack()
        Button(password_not_recog_screen, text="OK", command=delete_password_not_recognised).pack()

    def user_not_found(self):
        global user_not_found_screen
        user_not_found_screen = Toplevel(login_screen)
        user_not_found_screen.title("Success")
        user_not_found_screen.geometry("150x100")
        Label(user_not_found_screen, text="User Not Found").pack()
        Button(user_not_found_screen, text="OK", command=delete_user_not_found_screen).pack()


    def delete_login_success(self):
        login_success_screen.destroy(self)

    def delete_password_not_recognised(self):
        password_not_recog_screen.destroy(self)

    def delete_user_not_found_screen(self):
        user_not_found_screen.destroy(self)



class Menu(Frame):
    """Main menu"""
    def __init__(self, master):
        Frame.__init__(self, master)
        self.config(bg = "black")

        """Frame widgets"""
        label = Label(self, text = "Project Notes Presents Nutrition Calculator!\n Choose an option."\
                      , bg = "black", fg = "white")
        label.pack()
        button = Button(self, text = "Calculator", width = 20, command = lambda: master.switch(Calculator))
        button.pack(padx = 10, pady = 10)
        button2 = Button(self, text = "Add a product", width = 20, command = lambda: master.switch(File_Write))
        button2.pack()
        button3 = Button(self, text = "BMI Calculator", width = 20, command = lambda: master.switch(BMI))
        button3.pack(padx = 10, pady = 10)
        button4 = Button(self, text = "Exit", width = 20, command = self.close)
        button4.pack(padx = 10, pady = 10)


    def close(self):
        """Close the app"""
        self.destroy()
        exit()


class Calculator(Frame):
    """Writing nutritional values of the user defined food"""
    def __init__(self, master):
        Frame.__init__(self, master)
        self.config(bg = "black")

        def on_click():
            """Checking data and writing the results"""
            product = entryProduct.get()
            gram = entryGram.get()
            output.delete(0.0, END)

            Error = False
            try:
                gram = int(entryGram.get())
            except:
                Error = True
            try:
                x = int(product)
                Error = True
            except:
                pass
            if Error == True:
                messagebox.showerror("Error", "Please enter correct data!")
            else:
                functions.file_open()
                output.insert(END, functions.result(product, gram))

        """Frame widgets"""
        label = Label(self, text ="Enter a product that you ate.", bg = "black", fg = "white")
        label.pack()
        # user input, product
        label2 = Label(self, text = "Name: ", bg = "black", fg = "white")
        label2.pack()
        entryProduct = Entry(self, width = 20, bg = "white")
        entryProduct.pack()
        # user input, amount
        label3 = Label(self, text = "Amount: ", bg = "black", fg = "white")
        label3.pack()
        entryGram = Entry(self, width = 20, bg = "white")
        entryGram.pack()
        # submit
        submit = Button(self, text = "Submit", width = 8, command = on_click)
        submit.pack(padx = 10, pady = 10)
        # output
        label4 = Label(self, text = "These are the nutrition values:", bg = "black", fg = "white")
        label4.pack()
        output = Text(self, width = 20, height = 6, wrap = WORD, bg = "white")
        output.pack()
        #going back to menu
        self.button = Button(self, text = "Back", width = 8, command = lambda: master.switch(Menu))
        self.button.pack(padx = 10, pady = 10)


class File_Write(Frame):
    """User can add new new products and their values"""
    def __init__(self, master):
        Frame.__init__(self, master)
        self.config(bg = "black")

        def validate():
            """Checks is the user inputs correct data"""
            def write(name, kcal, protein, carb, fat):
                """Writes to file"""
                file = open("../../Downloads/PN-NutritionalCalculator/Products.txt", "a")
                productValue = "%s,%s:%s:%s:%s" % (name, kcal, protein, carb, fat)
                file.write("\n" + productValue)
                file.close()
                #Emptying inputs
                nameEntry.delete(0, END)
                kcalEntry.delete(0, END)
                proteinEntry.delete(0, END)
                carbEntry.delete(0, END)
                fatEntry.delete(0, END)

            error = False
            # checking if kcal, protein, carb and fat are integers and productName is a string
            try:
                name = int(nameEntry.get())
                error = True
            except:
                 name = nameEntry.get()
            try:
                kcal = int(kcalEntry.get())
                protein = int(proteinEntry.get())
                carb = int(carbEntry.get())
                fat = int(fatEntry.get())
            except:
                error = True
            if error == True:
                messagebox.showerror("Error", "Please enter correct data!")
            else:
                #writing to a file
                write(name, kcal, protein, carb, fat)

        """Frame widgets"""
        label = Label(self, text ="Enter the product name and its nutritional "\
                "values per 100 gram", bg = "black", fg = "white")
        label.pack()
        label1 = Label(self, text = "Name:", bg = "black", fg = "white")
        label1.pack()
        nameEntry = Entry(self, width = 20, bg = "white")
        nameEntry.pack()

        label2 = Label(self, text = "Calories:", bg = "black", fg = "white")
        label2.pack()
        kcalEntry = Entry(self, width = 20, bg = "white")
        kcalEntry.pack()

        label3 = Label(self, text = "Protein:", bg = "black", fg = "white")
        label3.pack()
        proteinEntry = Entry(self, width = 20, bg = "white")
        proteinEntry.pack()

        label4 = Label(self, text = "Carbs:", bg = "black", fg = "white")
        label4.pack()
        carbEntry = Entry(self, width = 20, bg = "white")
        carbEntry.pack()

        label5 = Label(self, text = "Fat:", bg = "black", fg = "white")
        label5.pack()
        fatEntry = Entry(self, width = 20, bg = "white")
        fatEntry.pack()

        submit = Button(self, text = "Submit", width = 8, command = validate)
        submit.pack(padx = 10, pady = 10)

        button3 = Button(self, text = "Back", width = 20, command = lambda: master.switch(Menu))
        button3.pack(padx = 10, pady = 10)

class BMI(Frame):
    """Writing nutritional values of the user defined food"""
    def __init__(self, master):
        Frame.__init__(self, master)
        self.config(bg = "black")

        def calculate_bmi(a=""):
            print(a)
            try:
                height = entryheight.get()
                weight = entryweight.get()
                height = float(height) / 100.0
                bmi = float(weight) / (height ** 2)
            except ZeroDivisionError:
                messagebox.showinfo("Result", "Please enter positive height!!")
            except ValueError:
                messagebox.showinfo("Result", "Please enter valid data!")
            else:
                if bmi <= 15.0:
                    res = "Your BMI is " + str(bmi) + "\nRemarks: Very severely underweight!!"
                    messagebox.showinfo("Result", res)
                elif 15.0 < bmi <= 16.0:
                    res = "Your BMI is " + str(bmi) + "\nRemarks: Severely underweight!"
                    messagebox.showinfo("Result", res)
                elif 16.0 < bmi < 18.5:
                    res = "Your BMI is " + str(bmi) + "\nRemarks: Underweight!"
                    messagebox.showinfo("Result", res)
                elif 18.5 <= bmi <= 25.0:
                    res = "Your BMI is " + str(bmi) + "\nRemarks: Normal."
                    messagebox.showinfo("Result", res)
                elif 25.0 < bmi <= 30:
                    res = "Your BMI is " + str(bmi) + "\nRemarks: Overweight."
                    messagebox.showinfo("Result", res)
                elif 30.0 < bmi <= 35.0:
                    res = "Your BMI is " + str(bmi) + "\nRemarks: Moderately obese!"
                    messagebox.showinfo("Result", res)
                elif 35.0 < bmi <= 40.0:
                    res = "Your BMI is " + str(bmi) + "\nRemarks: Severely obese!"
                    messagebox.showinfo("Result", res)
                else:
                    res = "Your BMI is " + str(bmi) + "\nRemarks: Super obese!!"
                    messagebox.showinfo("Result", res)


        """Frame widgets"""
        label = Label(self, text="Welcome to your BMI Calculator", bg="black", fg="white")
        label.pack()
        # user input, product
        label2 = Label(self, text="Weight (kg)", bg="black", fg="white")
        label2.pack()
        entryweight = Entry(self, width=20, bg="white")
        entryweight.pack()
        # user input, amount
        label3 = Label(self, text="Height(cm)", bg="black", fg="white")
        label3.pack()
        entryheight = Entry(self, width=20, bg="white")
        entryheight.pack()
        # submit
        submit = Button(self, text="Submit", width=8, command=calculate_bmi)
        submit.pack(padx=10, pady=10)
        # going back to menu
        self.button = Button(self, text="Back", width=8, command=lambda: master.switch(Menu))
        self.button.pack(padx=10, pady=10)

if __name__ == "__main__":
    app = App()
    app.mainloop()
AK 47

更新register類中方法Registercommand =在 lambda 表達式之前添加

Button(register_screen, text="Register", width=10, height=1, bg="lightseagreen", command = lambda: master.switch(Login)).pack()

對所有未command =在方法調用中定義關鍵字的實例重複此操作

比如login_success()類中方法Login也需要

Button(login_success_screen, text="OK", command = lambda: master.switch(Menu)).pack()

Este artigo é coletado da Internet.

Se houver alguma infração, entre em [email protected] Delete.

editar em
0

deixe-me dizer algumas palavras

0comentários
loginDepois de participar da revisão

Artigos relacionados

我試圖用我的 sql 創建一個外鍵,但我一直遇到錯誤

嘗試使用 gcc 編譯我的 opengl 項目時出現鏈接器錯誤

我的 textview 只是讓我底部溢出像素。我試過把它放到擴展的、singlechildscrollview 中,但仍然收到同樣的錯誤?

我在 Scala 中收到錯誤“錯誤:預期的類或對象定義”

Python 3.10 子進程錯誤:FileNotFoundError:[Errno 2] 沒有這樣的文件或目錄:'pkill'

Golang:嘗試刪除地圖中的項目時編譯錯誤

嘗試在新類中使用另一個類的方法時,我不斷收到位置參數錯誤

我該如何解決“應該只有一個具有 [DropdownButton] 值的項目:null。” 顫振中的錯誤?

當我收到錯誤“由更新版本的 Java 運行時(類文件版本 55.0)編譯...”時,如何將 JRE 或 JDK 設置為 IntelliJ 的 Java 11

我收到此錯誤類型錯誤:無法讀取未定義的屬性(正在讀取“用戶名”)

TypeScript 錯誤 7053 - 創建一個使用 prop 覆蓋樣式的自定義 React 組件,我如何正確告訴 TS 類型是什麼?

為什麼我收到一條錯誤消息,說不可散列列表?

Android Studio 中的 React Native 項目錯誤

JavaFX 項目錯誤:ImageIO 和 BufferedImage 不可見

Flutter 應用程序簡單登錄頁面,我在選擇 acc“'Future<dynamic>' 不是類型 '() => void' 的子類型後收到此錯誤”

編譯後將類添加到項目

我收到錯誤,但構建運行正確

我在 django 中收到錯誤報告“)預期”

翻譯成功,但進程一直在運行

Sed 錯誤 Github Actions 上沒有這樣的文件或目錄

我似乎無法找出為什麼我不斷收到錯誤“無效的方法聲明;需要返回類型”

Android studio 一直告訴我工廠類需要一個主體,可能有什麼問題?

編譯時類型未解析的 F# 類型錯誤

用 ts 製作一個 Discord 機器人,但我收到這個錯誤

NPM 啟動錯誤上的 ENOENT。為什麼我會收到這個錯誤,它為什麼要尋找“我的圖片”目錄?

為什麼在嘗試編譯時會收到未定義的引用錯誤?

str 不可調用錯誤。我正在用 python 製作一個狗頭勝過代碼,我想知道是否有人知道我為什麼會收到這個錯誤

我如何將android項目編譯為apk

編譯 Java 代碼時出現“不兼容類型錯誤”

TOP lista

  1. 1

    R Shiny: use HTML em funções (como textInput, checkboxGroupInput)

  2. 2

    O Chromium e o Firefox exibem as cores de maneira diferente e não sei qual deles está fazendo certo

  3. 3

    Como assinar digitalmente um documento PDF com assinatura e texto visíveis usando Java

  4. 4

    R Folheto. Dados de pontos de grupo em células para resumir muitos pontos de dados

  5. 5

    Gerenciar recurso shake de Windows Aero com barra de título personalizado

  6. 6

    Como obter dados API adequados para o aplicativo angular?

  7. 7

    UITextView não está exibindo texto longo

  8. 8

    Por que meus intervalos de confiança de 95% da minha regressão multivariada estão sendo plotados como uma linha de loess?

  9. 9

    Acessando relatório de campanhas na AdMob usando a API do Adsense

  10. 10

    Usando o plug-in Platform.js do Google

  11. 11

    Como posso modificar esse algoritmo de linha de visada para aceitar raios que passam pelos cantos?

  12. 12

    Dependência circular de diálogo personalizado

  13. 13

    Coloque uma caixa de texto HTML em uma imagem em uma posição fixa para site para desktop e celular

  14. 14

    iOS: como adicionar sombra projetada e sombra de traço no UIView?

  15. 15

    Como usar a caixa de diálogo de seleção de nomes com VBA para enviar e-mail para mais de um destinatário?

  16. 16

    Tabela CSS: barra de rolagem para a primeira coluna e largura automática para a coluna restante

  17. 17

    How to create dynamic navigation menu select from database using Codeigniter?

  18. 18

    Converter valores de linha SQL em colunas

  19. 19

    ChartJS, várias linhas no rótulo do gráfico de barras

  20. 20

    用@StyleableRes注释的getStyledAttributes。禁止警告

  21. 21

    não é possível adicionar dependência para com.google.android.gms.tasks.OnSuccessListener

quentelabel

Arquivo