Oct-20-2021, 08:08 PM
(This post was last modified: Oct-20-2021, 08:08 PM by deanhystad.)
What don't you understand about "super().__init__(parent, *args, bg=bg, **kwargs)"? Is this a "I don't understand subclassing" question or a "I don't understand super()" question or a "I don't understand this particular argument" question?
So your Entry class should have been named DictionaryEntry. I am going to assume that you want to use the DictionaryEntry class to display/edit an entry in a dictionary. DictionaryEntry has a label that displays the key name and a tk.Entry that displays/edits the value. When you change the value in the tk.Entry the DictionaryEntry object updates the entry value in the dictionary.
If that is correct, something like this should work.
So your Entry class should have been named DictionaryEntry. I am going to assume that you want to use the DictionaryEntry class to display/edit an entry in a dictionary. DictionaryEntry has a label that displays the key name and a tk.Entry that displays/edits the value. When you change the value in the tk.Entry the DictionaryEntry object updates the entry value in the dictionary.
If that is correct, something like this should work.
import tkinter as tk from tkinter import messagebox class DictionaryEntry(tk.Frame): '''Use me to display/edit a dictionary entry. Change entry value by typing in the Entry control and pressing <Return> or changing focus. I retain the type of the entry value. If the initial value is an int, I verify the Entry value is an int and display a message if it is not. ''' def __init__(self, parent, dictionary, key, bg=None, **kwargs): if bg is None: bg = parent['bg'] super().__init__(parent, bg=bg, **kwargs) self.dictionary = dictionary self.key = key value = dictionary[key] self.type = type(value) tk.Label(self, text=key, width=10).grid(row=0, column=0, sticky='E') self.variable = tk.StringVar(self, str(value)) entry = tk.Entry(self, textvariable=self.variable, width=10) entry.grid(row=0, column=1) entry.bind('<Return>', self._accept) entry.bind('<FocusOut>', self._accept) def _accept(self, event): '''Accept value change when return is pressed or losing focus''' try: value = self.type(self.variable.get()) self.dictionary[self.key] = value except ValueError: messagebox.showinfo('Value Error', f'{self.variable.get()} is not a {self.type.__name__}') self.variable.set(str(self.dictionary[self.value])) if __name__ == '__main__': dictionary = {'A':1, 'B':2.0, 'C':'string'} root = tk.Tk() for key in dictionary: DictionaryEntry(root, dictionary, key).pack(padx=10, pady=5) tk.Button(root, text="click me", command=lambda: print(dictionary)).pack(padx=10, pady=5) root.mainloop()