Python Forum
Checkbuttons always come up as black boxes regardless of the state
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Checkbuttons always come up as black boxes regardless of the state
#5
I was interested in your code and it inspired me to do a modified version. Just wanted to share. It's by far not the best way but, it works.
#! /usr/bin/env python3

# Do the imports
import pathlib
import os
import tkinter as tk
from tkinter import ttk
from functools import partial

# The main class
class MyClass:
    def __init__(self, parent):
        # Set the parent
        self.parent = parent
        self.parent.columnconfigure(0, weight=1)
        self.parent.rowconfigure(0, weight=1)

        # Container frame hold all other frames
        self.mainframe = tk.Frame(self.parent)
        self.mainframe.grid(column=0, row=0, sticky='new')
        self.mainframe.grid_columnconfigure(0, weight=3)

        # header frame
        self.label_frame = tk.Frame(self.mainframe)
        self.label_frame.grid(column=0, row=0, sticky='new')
        self.label_frame.grid_columnconfigure(0, weight=3)

        # The header label
        self.label = tk.Label(self.label_frame, anchor='n')
        self.label['text'] = 'Checkboxes'
        self.label['font'] = 'sans 16 bold'
        self.label['fg'] = 'blue'
        self.label.grid(column=0, row=0, sticky='new')
        self.label.grid_columnconfigure(0, weight=3)

        # The container frame for all the checkboxes
        self.checkbox_frame = tk.Frame(self.mainframe)
        self.checkbox_frame.grid(column=0, row=1, sticky='new')
        self.checkbox_frame.grid_columnconfigure(0, weight=3)

        # Initiate the files class for usage
        files = Files()
        file_path = GetPath().mypath()

        # Name of the settings file e.g. settings.txt
        file_name = 'settings.txt'

        # Create the file if it does not exist
        files.make_file(file_name)

        # This converts the settings.txt to integers for use in setting
        # the checkbox values to 0 or 1
        defaults = files.convert(file_name)

        # Set file variable
        file = f'{file_path}/{file_name}'

        # Setup some variables
        # vars is used to create a list to store checkbox settings
        # for sending to the Files class for writing
        vars = []

        # Used for setting rows and columns for checkboxes
        col_var = 0
        row_var = 0

        # Create the checkboxes
        for i in range(1,7):
            myvar = tk.IntVar()
            self.checkbox = ttk.Checkbutton(self.checkbox_frame)
            self.checkbox['text'] = f'Checkbox {i}'
            self.checkbox['variable'] = myvar

            # If there is not a defaults setting do nothing as we
            # have not saved any settings yet else we have some settings
            # go ahead and set the values
            if not defaults:
                pass
            else:
                myvar.set(defaults[i-1])

            self.checkbox.grid(column=col_var, row=row_var, sticky='new')
            if col_var >= 2:
                col_var = 0
                row_var += 1
            else:
                col_var += 1

            # Store checkbox settings in vars variable
            vars.append(myvar)

        # Setup the buttons
        self.btn_frame = tk.Frame(self.mainframe)
        self.btn_frame.grid(column=0, row=2, sticky='new', pady=10)
        self.btn_frame['relief'] = 'ridge'
        self.btn_frame['borderwidth'] = 1
        self.btn_frame.grid_columnconfigure(0, weight=3)

        self.btn = tk.Button(self.btn_frame, text='Save', command=partial(files.save, file, vars))
        self.btn.grid(column=0, row=0, sticky='w')

        self.btn = tk.Button(self.btn_frame, fg='red', text='Exit', command=os.sys.exit)
        self.btn.grid(column=1, row=0, sticky='e')


# Class to get current path
class GetPath:
    def mypath(self):
        return pathlib.Path(__file__).parent.absolute()


# Class for creating, writing, saving, and converting settings file
class Files:
    # File does not exist create or file exist pass
    def make_file(self, file):
        if not os.path.isfile(f'{GetPath().mypath()}/{file}'):
            open(f'{GetPath().mypath()}/{file}', 'w+')
        else:
            pass

    # Save the settings file
    def save(self, file, vars):
        try:
            myvars = []
            for val in vars:
                myvars.append(val.get())

            myf = open(file, 'w')
            myf.write(f'{myvars}')
            myf.close()

        except ValueError as error:
            print(error)

    # Convert the entries in the text file to integers to use in the Checkboxes
    # 0 for uncheck and 1 for checked. Set a variable list and return after conversion
    def convert(self, file):
        defaults = []
        with open(f'{GetPath().mypath()}/{file}', 'r') as lines:
            line = lines.read().replace('[','').replace(']','').replace(',','')

        line = line.split()
        for default in line:
            defaults.append(int(default))
        return defaults


def main():
    root = tk.Tk()
    root.title('Checkboxes')
    root.configure(borderwidth=3, relief='ridge', padx=10, pady=5)
    MyClass(root)
    root.mainloop()

if __name__ == '__main__':
    main()
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply


Messages In This Thread
RE: Checkbuttons always come up as black boxes regardless of the state - by menator01 - Jul-07-2020, 05:09 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Draw bounding boxes on live feed Jerome 0 363 Jan-20-2024, 10:50 PM
Last Post: Jerome
  remove all color but red, then replace it with black kucingkembar 14 7,414 Dec-29-2021, 07:50 PM
Last Post: deanhystad
  How to read check boxes from word document srikanthpython 0 2,671 Mar-30-2021, 01:58 PM
Last Post: srikanthpython
  How to use nb-black python cde formatter ErnestTBass 3 6,962 Jun-04-2020, 03:51 PM
Last Post: ErnestTBass
  Finance: Black Scholes Model not working pwt 5 4,040 May-27-2020, 10:14 AM
Last Post: buran
  after using openpyxl to add colors to script, black shows up white online in excel Soundtechscott 1 3,738 Jun-08-2019, 10:33 PM
Last Post: Soundtechscott
  State graph Kaluss 1 2,300 Mar-18-2019, 05:29 PM
Last Post: nilamo
  Because the emoji appears black and white at the exit ? nerd 3 5,682 Jan-28-2019, 11:34 PM
Last Post: nerd
  Help with plot, how to show ranking with boxes icebelt 1 2,501 Jan-25-2019, 10:00 AM
Last Post: Larz60+
  Python interface only black and white........ Wilson 3 6,259 Jul-15-2017, 01:20 PM
Last Post: sparkz_alot

Forum Jump:

User Panel Messages

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