С некоторыми изменениями это можно сделать, я попытался добавить как можно больше комментариев, чтобы помочь объяснить, почему.
import tkinter as tk
class fruits:
def __init__(self, name):
self.flag = 0
self.name = name
def clicked(e):
# Function that gets the selected value, then changes the flag property and prints the flag.
selected = e.widget.get(e.widget.curselection()) # Gets the index of the current selection and retrieves it's value.
all_fruits[selected].flag = 1
print(selected, "changed to", all_fruits[selected].flag)
test() # This is a function call to print the entire dictionary so changes can be seen.
def test():
# Function to print the all_fruits dictionary.
for k,v in all_fruits.items():
print(k, v.flag)
print()
root = tk.Tk()
#Main window
frame = tk.Frame(root)
frame.pack()
#Fruits selection
selectorlist = tk.Listbox(frame)
selectorlist.pack()
#Fruits creation
names = ['apple', 'pear', 'grape', 'orange', 'pineapple'] # List of fruit names.
all_fruits = {} # Define a dictionary for all fruits.
for name in names:
# Add each name as a dictionary key with the class as its value.
all_fruits[name] = fruits(name)
#List creation
for item in all_fruits:
# Insert each dictionary key into the listbox
selectorlist.insert(tk.END, item)
#Effect on click
selectorlist.bind("<<ListboxSelect>>", clicked) # Changed this to call a function
root.mainloop()
Для реализации функций Add / Remove было бы лучше реструктурировать класс так, чтобы существовал отдельный класс, управляющий всеми фруктами.
Я добавил несколько функций для добавления / удаления, которые могут быть полезны позже:
import tkinter as tk
class fruit:
"""A Class for each fruit."""
def __init__(self, name):
self.flag = 0
self.name = name
def change(self, value):
self.flag = value
class fruits:
"""A Class for all the fruits."""
def __init__(self):
self.all_fruits = {}
def add(self, listbox, name):
self.all_fruits[name] = fruit(name)
listbox.insert(tk.END, name)
print("Added", name)
def remove(self, listbox, name):
indx = listbox.get(0, tk.END).index(name)
listbox.delete(indx)
del self.all_fruits[name]
print("Deleted", name)
def change(self, name, value):
self.all_fruits[name].change(value)
def clicked(e):
# Function that gets the selected value, then changes the flag property and prints the flag.
selected = e.widget.get(e.widget.curselection()) # Gets the index of the current selection and retrieves it's value.
Fruits.change(selected, 1)
print(selected, "changed to 1")
test() # This is a function call to print the entire dictionary so changes can be seen.
def test():
# Function to print the all_fruits dictionary.
for k,v in Fruits.all_fruits.items():
print(k, v.flag)
print()
root = tk.Tk()
#Main window
frame = tk.Frame(root)
frame.pack()
#Fruits selection
selectorlist = tk.Listbox(frame)
selectorlist.pack()
#Fruits creation
names = ['apple', 'pear', 'grape', 'orange', 'pineapple', 'carrot'] # List of fruit names.
Fruits = fruits() # Creates an instance of fruits
for name in names:
Fruits.add(selectorlist, name) # Add each name with the class's add function.
Fruits.remove(selectorlist, "carrot")
#Effect on click
selectorlist.bind("<<ListboxSelect>>", clicked) # Changed this to call a function
root.mainloop()