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
#11
(Apr-20-2020, 10:42 PM)Larz60+ Wrote: 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

Thanks for working with me. So far, when I go to calculate, it does not calculate the numbers and throws errors.

However, mission accomplished with those buttons.

This is a tough one. I was practically banging my head against the wall on Saturday with it. This is much harder than I thought. I don't feel bad about not being able to figure this out on my own.
Reply
#12
Quote:it does not calculate the numbers and throws errors.
please show errors
did you see my edit at the bottom of last post? (i made a change to code)
When I run it, it works without a hitch (python 3.8.1, Linux Mint)
It the error something you can handle?
Reply
#13
Well if I could get my sides straight... LOL ...that might help it work properly.

This is all set! It works perfectly as long as the numbers are typed in the correct spot!

Thank you so much for your help! It is greatly appreciated. I look forward to working with you on here in the near and distant future and learning more as I continue my journey with the python language.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Creating a function interrupt button tkinter AnotherSam 2 5,503 Oct-07-2021, 02:56 PM
Last Post: AnotherSam
  [Tkinter] Open a python program from a button Pedroski55 3 4,983 Jul-20-2020, 11:09 PM
Last Post: Pedroski55
  [PySimpleGui] How to alter mouse click button of a standard submit button? skyerosebud 3 4,989 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,667 Oct-30-2018, 05:09 AM
Last Post: bhargavbn
  Tic-Tac-Toe restart gellerb 1 3,687 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