Andrew Sharov
Andrew Sharov

Reputation: 1

tkinter. checkbutton. How to understand what the user has chosen?

What should I do if the further development of my program depends on the selected "Checkbutton" ? What condition should I write down so that it is ahead of which Checkbutton the user clicked on??

c1 = IntVar()
c2 = IntVar()
c3 = IntVar()
c4 = IntVar()

che1 = Checkbutton( text="Первый флажок", variable=c1, font=('Arial', 24), onvalue=1, offvalue=0)
che2 = Checkbutton( text="Второй флажок", variable=c2, font=('Arial', 24), onvalue=2, offvalue=0)
che3 = Checkbutton( text="Третий флажок", variable=c3, font=('Arial', 24), onvalue=3, offvalue=0)
che4 = Checkbutton( text="Третий флажок", variable=c3, font=('Arial', 24), onvalue=4, offvalue=0)
che1.place(x=10, y=200)
che2.place(x=10, y=250)
che3.place(x=10, y=300)
che3.place(x=10, y=350)

Upvotes: 0

Views: 41

Answers (1)

Mike - SMT
Mike - SMT

Reputation: 15226

So here is a general use version of what you want.

First we define everything in a list to make it easier to add or remove options and easier to review what is selected.

In this case we use a list to hold your label names and then based on the index of those labels we set the Checkbutton location.

From there you can take the selected list and iterate over it to decide what to do next in your code.

Example:

import tkinter as tk


root = tk.Tk()
str_list = ["Первый флажок", "Второй флажок", "Третий флажок", "Третий флажок"]
c_list = []
selected = []

for ndex, value in enumerate(str_list):
    i = tk.IntVar()
    c = tk.Checkbutton(text=value, variable=i, font=('Arial', 24), onvalue=ndex + 1, offvalue=0)
    c_list.append([i, c, ndex])
    c_list[-1][1].grid(row=ndex, column=0)


def check_selected():
    global selected
    selected = []
    for lst in c_list:
        if lst[0].get() != 0:
            selected.append(lst[1]['text'])
            print(f'IntVar Value: {lst[0].get()}', f' - Label: {lst[1]["text"]}', f' - List index: {lst[2]}')


tk.Button(root, text='Selections', command=check_selected).grid(row=len(str_list), column=0)
root.mainloop()

Results:

enter image description here

IntVar Value: 1  - Label: Первый флажок  - List index: 0
IntVar Value: 3  - Label: Третий флажок  - List index: 2

Upvotes: 0

Related Questions