mardi 8 août 2023

Tkinter - GUI: checkbox with button that checks for exceptions and closes window

I am creating a GUI that will display the option to the user with a checkbox, and then after pressing the "Enter Data" button the program will check if the user has pressed at least one of the check-boxes. The checked values are being assigned to a dictionary which will be used later down the code. I am trying to make the button only close the window if no exception is raised (i.e. at least one check box is checked).

Right now the program displays the exception message no matter what, even if the user has checked at least 1 checkbox.

import tkinter
from tkinter import *
from tkinter import ttk
from tkinter import messagebox

def enter_data():
    global fatigue_vars

    try:
        if any(fatigue_vars):
            raise Exception("Please select at least one (1) of the given checkboxes!")
            return
    except Exception as ex:
        tkinter.messagebox.showwarning(title="Selection Error!", message=ex)
        return

    window.destroy()

#GUI 

window = tkinter.Tk()
window.title("Dimensions Data Entry")
window.resizable(0,0)

frame = tkinter.Frame(window)
frame.pack()

def disable_event():
    pass
window.protocol("WM_DELETE_WINDOW", disable_event)

#FATIGUE CASE

fatigue_type_frame =tkinter.LabelFrame(frame, text="Fatigue Type")
fatigue_type_frame.grid(row= 0, column=0, padx=20, pady=10)

fatigue_type_option=["Tension", "Compression", "Torsion", "Bending"]

fatigue_vars = {}
for fatigue_type in fatigue_type_option:
    var = StringVar(value="")
    fatigue_vars[fatigue_type] = var
    check_button= Checkbutton(
        fatigue_type_frame,
        text=fatigue_type,
        variable=var,
        onvalue=fatigue_type,
        offvalue="",
        padx=20,
        pady=10
    )

for widget in fatigue_type_frame.winfo_children():
    widget.grid_configure(padx=10, pady=5)

# ENTER DATA BUTTON
button = tkinter.Button(frame, text="Enter Data", command=enter_data)
button.grid(row=2, column=0, sticky="news", padx=20, pady=10)

window.mainloop()



Aucun commentaire:

Enregistrer un commentaire