|
| 1 | + |
| 2 | +# author: Bartlomiej "furas" Burek (https://blog.furas.pl) |
| 3 | +# date: 2021.05.30 |
| 4 | +# |
| 5 | +# title: How to get the updated entry string from a toplevel window before the tkinter main loop ends? |
| 6 | +# url: https://stackoverflow.com/questions/67754560/how-to-get-the-updated-entry-string-from-a-toplevel-window-before-the-tkinter-ma/67756653#67756653 |
| 7 | + |
| 8 | +import tkinter as tk |
| 9 | + |
| 10 | + |
| 11 | +class NameInputBox: |
| 12 | + |
| 13 | + entry_value = 'Empty String' |
| 14 | + |
| 15 | + def __init__(self, text): |
| 16 | + |
| 17 | + self.window = tk.Toplevel() |
| 18 | + self.window.wm_title('Input Name.') |
| 19 | + |
| 20 | + self.label = tk.Label(self.window, text=text) |
| 21 | + self.label.pack(side='top') |
| 22 | + |
| 23 | + self.frame = tk.Frame(self.window) |
| 24 | + self.frame.pack(side='bottom') |
| 25 | + |
| 26 | + self.entry = tk.Entry(self.frame) |
| 27 | + self.entry.pack(side='left') |
| 28 | + |
| 29 | + self.button = tk.Button(self.frame, text="Ok", command=self.name_input_box_exit) |
| 30 | + self.button.pack(side='left') |
| 31 | + |
| 32 | + def name_input_box_exit(self): |
| 33 | + self.entry_value = self.entry.get() |
| 34 | + self.window.destroy() |
| 35 | + |
| 36 | + |
| 37 | +class MainWindow: |
| 38 | + def __init__(self): |
| 39 | + self.window = tk.Tk() |
| 40 | + |
| 41 | + self.label = tk.Label(self.window) |
| 42 | + self.label.pack() |
| 43 | + |
| 44 | + self.button = tk.Button(self.window, text='Name', command=self.ask_name) |
| 45 | + self.button.pack() |
| 46 | + |
| 47 | + # the only mainloop in all code |
| 48 | + self.window.mainloop() |
| 49 | + |
| 50 | + def ask_name(self): |
| 51 | + # show Toplevel |
| 52 | + self.box = NameInputBox('Input the Name:') |
| 53 | + |
| 54 | + # set it modal (to wait for value) |
| 55 | + self.box.window.focus_set() # take over input focus, |
| 56 | + self.box.window.grab_set() # disable other windows while it is open, |
| 57 | + self.box.window.wait_window() # and wait here until window destroyed |
| 58 | + |
| 59 | + # get value from Toplevel |
| 60 | + self.label['text'] = self.box.entry_value |
| 61 | + |
| 62 | +if __name__ == '__main__': |
| 63 | + MainWindow() |
0 commit comments