Если вы создали словарь, например
check_boxes = {'pizza': IntVar(), ...}
, вам следует использовать keys
и values
из словаря
В key
вы получите текст 'pizza'
, который вам нужен
def confirm():
for key, item in check_boxes.items():
if item.get() == 1:
print(key)
import tkinter as tk
# from tkinter import * # PEP8: `import *` is not preferred
# --- functions ---
def confirm():
for key, item in check_boxes.items():
if item.get() == 1:
print(key)
# --- main ---
my_items = ['pizza', 'breadsticks', 'wings', 'CocaCola', 'brownie']
root = tk.Tk()
check_boxes = {item:tk.IntVar() for item in my_items}
for item in my_items:
cb = tk.Checkbutton(root, text=item, variable=check_boxes[item], anchor='w', onvalue=1, offvalue=0, width=50)
cb.pack()
b1 = tk.Button(root, text="confirm", command=confirm) # PEP8: without spaces around `=`, `lower_case_names` for variables
b1.pack()
root.mainloop()
Кстати: Вы также можете использовать StringVar()
и onvalue='pizza'
import tkinter as tk
# --- functions ---
def confirm():
for string_var in check_boxes:
text = string_var.get()
if text:
print(text)
# --- main ---
my_items = ['pizza', 'breadsticks', 'wings', 'CocaCola', 'brownie']
root = tk.Tk()
check_boxes = []
for item in my_items:
string_var = tk.StringVar()
check_boxes.append(string_var)
cb = tk.Checkbutton(root, text=item, variable=string_var, anchor='w', onvalue=item, offvalue='', width=50)
cb.pack()
b1 = tk.Button(root, text="confirm", command=confirm)
b1.pack()
root.mainloop()