Python Forum
[Tkinter] Creating a restart button for a Pythagorean Theorem Program
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] Creating a restart button for a Pythagorean Theorem Program
#1
Hi All,

This is my first post on this forum. I'm really excited to be a part of this community. What I'm trying to do here is I'm trying to make a restart button for this Tkinter Pythagorean theorem calculator. I found this online, but I wanted to change it up a little bit to add the reset button for no matter which one I am solving for.

SO, if I am solving for A, B or C, I want there to be a reset button once I get done with making a calculation. I want it to take me back to the beginning of the app.

I am new to python, and I really want to learn. This can be a great learning experience, and every time I learn something new, it makes me stronger.

Thank you.

from tkinter import *
from math import sqrt
root=Tk()
root.title("Pythagorean Theorem Calculator")
root.geometry("400x70")

f1=Frame(root, width=400, height=20)
f1.pack()
f2=Frame(root, width=420, height=20)
f2.pack()

var_a=StringVar()
var_b=StringVar()
var_c=StringVar()

# Initial welcome; then asks which side of triangle to solve for
def start():
    welcome_label=Label(f1, text="Welcome to the Pythagorean Theorem Calculator!", fg="blue")
    solve_for=Label(f1, text="Would you like to solve for A, B, or C?")
    button_a=Button(f2, text="Solve for A", fg="green", command = solve_a)
    button_b=Button(f2, text="Solve for B", fg="green", command = solve_b)
    button_c=Button(f2, text="Solve for C", fg="green", command = solve_c)

    welcome_label.pack()
    solve_for.pack()
    button_a.pack(side=LEFT)
    button_b.pack(side=LEFT)
    button_c.pack(side=LEFT)


# Math, labels, buttons, and frames to solve for A
def solve_a():
    f1.pack_forget()
    f2.pack_forget()
    new_frame=Frame(root)
    new_frame.pack()

    def ans_a():
        new_frame.pack_forget()
        new_frame1=Frame(root)
        new_frame1.pack()
        value_b=float(var_b.get())
        value_c=float(var_c.get())
        a=sqrt((value_c**2)-(value_b**2))
        ans=Label(new_frame1, text=("The value of A is: "+str(a)))
        ans.pack()


    label_b=Label(new_frame, text="Value of B:")
    label_c=Label(new_frame, text="Value of C:")
    e1=Entry(new_frame, textvariable=var_b)
    e2=Entry(new_frame, textvariable=var_c)
    submit=Button(new_frame, text="Submit", fg="red", command=ans_a)

    label_b.grid(row=0, sticky=W)
    label_c.grid(row=1, sticky=W)
    e1.grid(row=0, column=1)
    e2.grid(row=1, column=1)
    submit.grid(row=2, column=1)



# Math, labels, buttons, and frames to solve for B
def solve_b():
    f1.pack_forget()
    f2.pack_forget()
    new_frame=Frame(root)
    new_frame.pack()

    def ans_b():
        new_frame.pack_forget()
        new_frame1=Frame(root)
        new_frame1.pack()
        value_a=float(var_a.get())
        value_c=float(var_c.get())
        b=sqrt((value_c**2)-(value_a**2))
        ans=Label(new_frame1, text=("The value of B is: "+str(b)))
        ans.pack()

    label_a=Label(new_frame, text="Value of A:")
    label_c=Label(new_frame, text="Value of C:")
    e1=Entry(new_frame, textvariable=var_a)
    e2=Entry(new_frame, textvariable=var_c)
    submit=Button(new_frame, text="Submit", fg="red", command=ans_b)

    label_a.grid(row=0, sticky=W)
    label_c.grid(row=1, sticky=W)
    e1.grid(row=0, column=1)
    e2.grid(row=1, column=1)
    submit.grid(row=2, column=1)



# Math, labels, buttons, and frames to solve for C
def solve_c():
    f1.pack_forget()
    f2.pack_forget()
    new_frame=Frame(root)
    new_frame.pack()

    def ans_c():
        new_frame.pack_forget()
        new_frame1=Frame(root)
        new_frame1.pack()
        value_a=float(var_a.get())
        value_b=float(var_b.get())
        c=sqrt((value_a**2)+(value_b**2))
        ans=Label(new_frame1, text=("The value of C is: "+str(c)))
        ans.pack()

    label_a=Label(new_frame, text="Value of A:")
    label_b=Label(new_frame, text="Value of B:")
    e1=Entry(new_frame, textvariable=var_a)
    e2=Entry(new_frame, textvariable=var_b)
    submit=Button(new_frame, text="Submit", fg="red", command=ans_c)

    label_a.grid(row=0, sticky=W)
    label_b.grid(row=1, sticky=W)
    e1.grid(row=0, column=1)
    e2.grid(row=1, column=1)
    submit.grid(row=2, column=1)


# Calls the initial welcome screen
start()
root.mainloop()
Reply
#2
I can give you some help with this, but will be in my am EDT, about 12 hours fro now.
Reply
#3
(Apr-19-2020, 02:30 AM)Larz60+ Wrote: I can give you some help with this, but will be in my am EDT, about 12 hours fro now.

That would be awesome! I will check back around then.
Reply
#4
Here's the front end, I have a few errands that must be done, will add your solutions when done.
But you can absorb this (it can be run, but no solutions yet):
import tkinter as tk
from math import sqrt


class PythagoreanTheorem:
    def __init__(self, parent):
        self.parent = parent
        self.parent.title("Pythagorean Theorem Calculator")
        self.parent.geometry("400x70")

        self.buttons = {}
        self.add_widgets()

    def solve_equation(self, event, name):
        print(f"solve for {name}")

    def add_widgets(self):
        buttons = self.buttons

        f1 = tk.Frame(self.parent, width=400, height=20)
        welcome_label = tk.Label(f1,
            text="Welcome to the Pythagorean Theorem Calculator!",
            fg="blue")

        solve_for = tk.Label(f1, text="Would you like to solve for A, B, or C?")

        f1.pack()
        welcome_label.pack()
        solve_for.pack()

        f2 = tk.Frame(self.parent, width=420, height=20)
        for name in ['A', 'B', 'C']:
            self.buttons[name] = {}
            self.buttons[name]['name'] = name
            self.buttons[name]['button'] =  tk.Button(f2, fg="green", text=f"Solve for {name}")
            self.buttons[name]['button'].bind('<Button-1>', lambda event, bname=self.buttons[name]['name']: self.solve_equation(event, bname))
            self.buttons[name]['button'].pack(side=tk.LEFT)
        f2.pack()

def main():
    root = tk.Tk()
    pt = PythagoreanTheorem(root)
    root.mainloop()


if __name__ == "__main__":
    main()
EDIT 4-19-2020 11:18 EDT changed line 35 fg is green, not bg
Reply
#5
Please, I want to make sure that you're not offended by my drastic changes before I continue.
Reply
#6
(Apr-20-2020, 10:46 AM)Larz60+ Wrote: Please, I want to make sure that you're not offended by my drastic changes before I continue.

Not at all. Your help is greatly appreciated.
Reply
#7
Still working
Reply
#8
(Apr-20-2020, 06:25 PM)Larz60+ Wrote: Still working

OK. Thanks for checking in! Look forward to seeing solution soon.

I guess it was more difficult than I thought.
Reply
#9
tricky to do correctly, also doing this between moderator tasks and my own company work.
Reply
#10
OK, I'm pretty sure I got all of the bugs out:
Try and let me know what you think.
This could be simplified even more, but it would start to get cryptic if so.

import tkinter as tk
from math import sqrt
import sys


class PythagoreanTheorem:
    def __init__(self, parent):
        self.parent = parent
        self.levelwidth = 400
        self.levelheight = 80
        self.levelxpos = 400
        self.levelypos = 400
        self.parent.title("Pythagorean Theorem Calculator")
        self.parent.geometry("400x80")
        self.parent.geometry(f"{self.levelwidth}x{self.levelheight}" \
            f"+{self.levelxpos}+{self.levelypos}")
 
        self.name = None
        self.var_1 = tk.StringVar()
        self.var_2 = tk.StringVar()

        self.buttons = {}

        self.parent.withdraw()

        self.choice_frame = tk.Toplevel()
        handler = lambda: self.onCloseFrame(self.choice_frame, self.query_frame)
        self.add_choice_frame()

        self.query_frame = tk.Toplevel()
        handler = lambda: self.onCloseFrame(self.query_frame, self.results_frame)
        self.add_query_frame()
        self.query_frame.withdraw()

        self.results_frame = tk.Toplevel()
        handler = lambda: self.onCloseFrame(self.results_frame, self.choice_frame)
        self.add_results_frame()
        self.results_frame.withdraw()

        self.choice_frame.lift()

    def solve_equation(self, event, name):
        self.name = name
        self.e1.delete(0, 'end')
        self.e2.delete(0, 'end')

        if name == 'next':
            self.results_frame.withdraw()
            self.choice_frame.deiconify()
        elif name == 'A':            
            self.choice_frame.withdraw()
            self.query_frame.deiconify()
            self.label_1.configure(text="Value of B:")
            self.label_2.configure(text="Value of C:")
        elif name == 'B':
            self.choice_frame.withdraw()
            self.query_frame.deiconify()
            self.label_1.configure(text="Value of A:")
            self.label_2.configure(text="Value of C:")
        elif name == 'C':
            self.choice_frame.withdraw()
            self.query_frame.deiconify()
            self.label_1.configure(text="Value of A:")
            self.label_2.configure(text="Value of B:")
        else:
            print(f"Unknown name {name}")
            sys.exit(-1)

    def onCloseFrame(self, oldframename):
        oldframename.withdraw()
        newframename.deconify()

    def add_choice_frame(self):
        self.choice_frame.title("Pythagorean Theorem Calculator")
        self.choice_frame.geometry(f"{self.levelwidth}x{self.levelheight}" \
            f"+{self.levelxpos}+{self.levelypos}")
        self.choice_frame.protocol('WM_DELETE_WINDOW', self.quit)

        self.f1 = tk.Frame(self.choice_frame, width=400, height=40)
        self.f1.pack()

        welcome_label = tk.Label(self.f1,
            text="Welcome to the Pythagorean Theorem Calculator!", fg="blue")
        welcome_label.pack()
 
        solve_for = tk.Label(self.f1, text="Would you like to solve for A, B, or C?")
        solve_for.pack()
 

        self.f2 = tk.Frame(self.choice_frame, width=420, height=20)
        self.f2.pack()

        for name in ['A', 'B', 'C']:
            self.buttons[name] = {}
            self.buttons[name]['name'] = name
            self.buttons[name]['button'] =  tk.Button(self.f2, fg="green", text=f"Solve for {name}")
            self.buttons[name]['button'].bind('<Button-1>', lambda event, bname=self.buttons[name]['name']: self.solve_equation(event, bname))
            self.buttons[name]['button'].pack(side=tk.LEFT)

    def add_query_frame(self):
        self.query_frame.title("Pythagorean Theorem Calculator")
        self.query_frame.geometry(f"{self.levelwidth}x{self.levelheight}" \
            f"+{self.levelxpos}+{self.levelypos}")
        self.query_frame.protocol('WM_DELETE_WINDOW', self.quit)

        self.label_1 = tk.Label(self.query_frame)
        self.label_2 = tk.Label(self.query_frame)

        self.e1 = tk.Entry(self.query_frame, textvariable=self.var_1)
        self.e2 = tk.Entry(self.query_frame, textvariable=self.var_2)

        self.submit_button = tk.Button(self.query_frame, text="Submit", fg="red", command=self.submit)

        self.label_1.grid(row=0, sticky='w')
        self.label_2.grid(row=1, sticky='w')
        self.e1.grid(row=0, column=1)
        self.e2.grid(row=1, column=1)
        self.submit_button.grid(row=2, column=1)

    def add_results_frame(self):
        self.results_frame.title("Pythagorean Theorem Calculator")
        self.results_frame.geometry(f"{self.levelwidth}x{self.levelheight}" \
            f"+{self.levelxpos}+{self.levelypos}")
        self.query_frame.protocol('WM_DELETE_WINDOW', self.quit)

        self.result_label = tk.Label(self.results_frame)
        self.result_label.pack()

        self.next_button = tk.Button(self.results_frame, text="Next", fg="green")
        self.next_button.bind('<Button-1>', lambda event, bname=self.next_button: self.solve_equation(event, 'next'))
        self.next_button.pack(side=tk.LEFT)

        self.quit_button = tk.Button(self.results_frame, text="Quit", fg="red", command=quit)
        self.quit_button.pack(side=tk.LEFT)

    def submit(self):
        self.query_frame.withdraw()
        self.results_frame.deiconify()
        self.show_results()

    def show_results(self):
        name = self.name
        value1 = float(self.var_1.get())
        value2 = float(self.var_2.get())

        if name == 'C':
            result = sqrt((value1 ** 2) + (value2 ** 2))
        else:
            result = sqrt((value1 ** 2) - (value2 ** 2))
        self.result_label.configure(text = f"The value of {name} is: {str(result)}")


    def quit(self):
        self.parent.destroy()
        sys.exit(0)


def main():
    root = tk.Tk()
    pt = PythagoreanTheorem(root)
    root.mainloop()
 

if __name__ == "__main__":
    main()
You can get display dimensions using (so you can calculate display center):
from win32api import GetSystemMetrics

Width = {GetSystemMetrics(0)}
Height = {GetSystemMetrics(1)}
EDIT 10:43 PM UTC fixed error in calculation
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Creating a function interrupt button tkinter AnotherSam 2 5,564 Oct-07-2021, 02:56 PM
Last Post: AnotherSam
  [Tkinter] Open a python program from a button Pedroski55 3 5,034 Jul-20-2020, 11:09 PM
Last Post: Pedroski55
  [PySimpleGui] How to alter mouse click button of a standard submit button? skyerosebud 3 5,038 Jul-21-2019, 06:02 PM
Last Post: FullOfHelp
  [PyQt] Close program using Push Button with the help of input from a Message Box bhargavbn 2 6,697 Oct-30-2018, 05:09 AM
Last Post: bhargavbn
  Tic-Tac-Toe restart gellerb 1 3,701 Apr-25-2018, 08:56 PM
Last Post: woooee

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020