Search code examples
pythonexceptiontkintercheckboxtkinter-button

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 option_vars

    try:
        if any(option_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("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

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

option_type_option=["Type 1", "Type 2", "Type 3", "Type 4"]

option_vars = {}
for option_type in option_type_option:
    var = StringVar(value="")
    option_vars[option_type] = var
    check_button= Checkbutton(
        option_type_frame,
        text=option_type,
        variable=var,
        onvalue=option_type,
        offvalue="",
        padx=20,
        pady=10
    )

for widget in option_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()

Solution

  • The issue is any(option_vars) will always return True as it is checking that the dictionary items exist in that instance.

    What you intend to do is check if none of the values exist, this is further complicated because the values are in a StringVar, but can be accomplished by iterating the dictionary values, then calling a get() from the StringVar:

    if not any([i.get() for i in option_vars.values()]):