Изменить атрибут из экземпляра с помощью списка tkinter - PullRequest
1 голос
/ 15 апреля 2020

Я новичок здесь, и я новичок в tkinter. Я хочу изменить атрибут указанного экземпляра c из класса. Чтобы выбрать экземпляр, я хочу использовать список. Вот простая версия кода для создания списка. Можно ли изменить атрибут флага выбранного экземпляра (если на apple нажата кнопка мыши, измените значение apple.flag на 1)?

Спасибо!

import tkinter as tk

class fruits:
    all_fruits = []
    def __init__(self,name):
        self.flag = 0
        self.name = name
        fruits.all_fruits.append(self.name)

root = tk.Tk()
#Main window
frame = tk.Frame(root)
frame.pack()
#Fruits selection
selectorlist = tk.Listbox(frame)
selectorlist.pack()

#Fruits creation
apple = fruits('apple')
pear = fruits('pear')

#List creation
for item in fruits.all_fruits:
        selectorlist.insert(tk.END, item)

#Effect on click
selectorlist.bind("<Button-1>",lambda *a: print("Flag is 1"))
root.mainloop()

1 Ответ

0 голосов
/ 15 апреля 2020

С некоторыми изменениями это можно сделать, я попытался добавить как можно больше комментариев, чтобы помочь объяснить, почему.

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()

enter image description here

Для реализации функций 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()

enter image description here

...