How To Get Variables From Toplevel Window To Main Window?
I have a code that gets keyinputs and show it on a entrybox in the toplevel window of the main window. In the main window I have a listbox and I am wishing to get the keyinput that
Solution 1:
To get values from one class to another class you've to link them. Inheriting the Widgets directly to the class will help you a lot in establishing a connection between Tk()
window and Toplevel()
Window.
One more thing when a Keyboard
window is already opened disable the button by configure state = 'disabled'
so the user won't open another one by mistake and when Keyboard
window is closed re-enable the button by state = 'normal'
.
Here is the complete code:
import tkinter as tk
import tkinter.ttk as ttk
classEntryBox(tk.Entry):
def__init__(self, master, cnf = {}, **kw):
kw = tk._cnfmerge((kw, cnf))
kw['justify'] = kw.get('justify', 'center')
kw['width'] = 15
kw['state'] = 'readonly'super(EntryBox, self).__init__(master=master, **kw)
self.bind_class(self, '<Key>', self._display)
def_display(self, evt):
self['state'] = 'normal'
self.delete('0', 'end')
self.insert('0', str(evt.keysym))
self['state'] = 'readonly'classKeyboard(tk.Toplevel):
def__init__(self, master=None, cnf={}, **kw):
super(Keyboard, self).__init__(master=master, cnf=cnf, **kw)
self.master = master
kb_frame = ttk.Frame(self)
kb_frame.grid(column=0, row=1, pady=(7, 19))
ttk.Label(kb_frame, text='Enter Key').grid(column=0, row=0, pady=4)
self.entry = EntryBox(kb_frame)
self.entry.grid(column=0, row=1)
# This protocol calls the function when clicked on 'x' on titlebar
self.protocol("WM_DELETE_WINDOW", self.Destroy)
# Confirm button
self.co_button = ttk.Button(self, text='Confirm', command=self.on_press)
self.co_button.grid(column=0, row=2)
defon_press(self):
key = self.entry.get()
# Condition to not have duplicate values, If you want to have duplicate values remove the conditionif key notin self.master.lb.get('0', 'end') and key:
# Insert the Key to the listbox of mainwindow
self.master.lb.insert('end', key)
defDestroy(self):
# Enable the button
self.master.kb_button['state'] = 'normal'# Then destroy the window
self.destroy()
classMain(tk.Tk):
def__init__(self):
super(Main, self).__init__()
bt_frame = ttk.Frame(self)
bt_frame.grid(column=2, row=0, rowspan=2)
self.kb_button = ttk.Button(bt_frame, text='KeyBoard', command=self.on_press)
self.kb_button.grid(column=0, row=0)
self.lb = tk.Listbox(bt_frame)
self.lb.grid(column=0, row=1)
defon_press(self):
# Creating a toplevel window and passed self as master parameter
self.Kb = Keyboard(self)
# Disabled the button
self.kb_button['state'] = 'disabled'
main = Main()
main.mainloop()
Post a Comment for "How To Get Variables From Toplevel Window To Main Window?"