2025-11-24_tk-windows-in-python.html


001| #:name::Tk Windows in Python
002| #:link::https://thehardcorecoder.com/2025/11/24/windows-in-python-using-tk/
003| #:date::2025-11-24
004| #:code::
005| import tkinter as tk
006| 
007| # Create a window...
008| tk.Tk()
009| 
010| #:code::
011| import tkinter as tk
012| 
013| # Create a window (save return value)...
014| root = tk.Tk()
015| 
016| #:code::
017| import tkinter as tk
018| 
019| # Create a window; set title; set geometry...
020| root = tk.Tk()
021| root.title('A Simple Window')
022| root.geometry('480x240+300+100')
023| 
024| #:code::
025| import tkinter as tk
026| 
027| # Create a window; set title; set geometry...
028| root = tk.Tk()
029| root.title('A Simple Window')
030| root.geometry('480x240+300+100')
031| 
032| # Start the window loop...
033| root.mainloop()
034| 
035| #:code::
036| import tkinter as tk
037| 
038| def open_the_window (ttl='The Window', geo='480x240+300+100'):
039|     '''Create a new window.'''
040| 
041|     # Create window; set title & geometry...
042|     root = tk.Tk()
043|     root.title(ttl)
044|     root.geometry(geo)
045| 
046|     # Return root object...
047|     return root
048| 
049| 
050| if __name__ == '__main__':
051|     print()
052|     # Create the window...
053|     app = open_the_window()
054| 
055|     # Start the window loop...
056|     app.mainloop()
057|     print()
058| 
059| #:code::
060| import tkinter as tk
061| 
062| def open_the_window (ttl='The Window', geo='480x240+300+100'):
063|     '''Create a new window.'''
064|     root = tk.Tk()
065|     root.title(ttl)
066|     root.geometry(geo)
067| 
068|     def window_close ():
069|         '''Close the window.'''
070|         # Destroy the main window...
071|         # (Returns us from mainloop.)
072|         root.destroy()
073| 
074|     # Create simple menubar...
075|     menubar = tk.Menu(root)
076| 
077|     # Add a command to the menubar...
078|     menubar.add_command(label='Exit', command=window_close)
079| 
080|     # Add menubar to main window...
081|     root.config(menu=menubar)
082| 
083|     # Return root object...
084|     return root
085| 
086| 
087| if __name__ == '__main__':
088|     print()
089|     # Create the window...
090|     app = open_the_window()
091| 
092|     # Start the window loop...
093|     app.mainloop()
094|     print()
095| 
096| #:code::
097| import tkinter as tk
098| import tkinter.messagebox as msgbox
099| 
100| def open_the_window (ttl='The Window', geo='480x240+300+100'):
101|     '''Create a new window.'''
102|     root = tk.Tk()
103|     root.title(ttl)
104|     root.geometry(geo)
105| 
106|     def window_close ():
107|         '''Close the window.'''
108|         root.destroy()
109| 
110|     def about ():
111|         '''Popup the About message box.'''
112|         msgbox.showinfo('About', 'Simple Tk Application.')
113| 
114|     # Create simple menubar...
115|     menubar = tk.Menu(root)
116|     menubar.add_command(label='Exit', command=window_close)
117|     menubar.add_separator()
118|     menubar.add_command(label='About', command=about)
119|     # Add menubar to main window...
120|     root.config(menu=menubar)
121| 
122|     # Return root object...
123|     return root
124| 
125| 
126| if __name__ == '__main__':
127|     print()
128| 
129|     # Create window and loop...
130|     app = open_the_window()
131|     app.mainloop()
132|     print()
133| 
134| #:code::
135| import tkinter as tk
136| import tkinter.messagebox as msgbox
137| 
138| def open_the_window (ttl='The Window', geo='480x240+300+100'):
139|     '''Create a new window.'''
140| 
141|     def menu_command ():
142|         '''Handle menu selection.'''
143|         print('Menu Choice.') #ATTN: not helpful!
144| 
145|     def window_close (): #ATTN: bug!
146|         '''Close the window.'''
147|         root.destroy()
148| 
149|     def about ():
150|         '''Popup the About message box.'''
151|         msgbox.showinfo('About', 'Simple Tk Application.')
152| 
153|     def build_menubar ():
154|         ''' Create real menubar.'''
155|         menubar = tk.Menu(root)
156| 
157|         # Create File Sub-Menu...
158|         mbarFile = tk.Menu(menubar, name='fileMenu', tearoff=0)
159|         mbarFile.add_command(label='New', command=menu_command)
160|         mbarFile.add_command(label='Open...', command=menu_command)
161|         mbarFile.add_command(label='Save', command=menu_command)
162|         mbarFile.add_command(label='Save As...', command=menu_command)
163|         mbarFile.add_separator()
164|         mbarFile.add_command(label='Exit', command=window_close)
165| 
166|         # Create Edit Sub-Menu...
167|         mbarEdit = tk.Menu(menubar, name='editMenu', tearoff=0)
168|         mbarEdit.add_command(label='Copy' , command=menu_command)
169|         mbarEdit.add_command(label='Paste', command=menu_command)
170| 
171|         # Create Help Sub-Menu...
172|         mbarHelp = tk.Menu(menubar, name='helpMenu', tearoff=0)
173|         mbarHelp.add_command(label='About', command=about)
174| 
175|         # Add sub-menus to MenuBar...
176|         menubar.add_cascade(label='File', menu=mbarFile, underline=0)
177|         menubar.add_cascade(label='Edit', menu=mbarEdit, underline=0)
178|         menubar.add_cascade(label='Help', menu=mbarHelp, underline=0)
179| 
180|         # Add menubar to main window...
181|         root.config(menu=menubar)
182| 
183|     # Open-The-Window thread starts here...
184|     root = tk.Tk()
185|     root.title(ttl)
186|     root.geometry(geo)
187|     root.bind('<Escape>', window_close)
188| 
189|     # Return root object...
190|     build_menubar()
191|     return root
192| 
193| 
194| if __name__ == '__main__':
195|     print()
196|     app = open_the_window()
197|     app.mainloop()
198|     print()
199| 
200| #:code::
201| import tkinter as tk
202| import tkinter.messagebox as msgbox
203| 
204| def open_the_window (ttl='The Window', geo='480x240+300+100'):
205|     '''Create a new window.'''
206| 
207|     def menu_command (*args):
208|         print(f'Menu Choice: {args[0]}')
209| 
210|     def window_close (*args):
211|         '''Close the window.'''
212|         root.destroy()
213| 
214|     def about (*args):
215|         '''Popup the About message box.'''
216|         msgbox.showinfo('About', 'Simple Tk Application.')
217| 
218|     def build_menubar ():
219|         ''' Create menubar.'''
220|         menubar = tk.Menu(root)
221| 
222|         def proxy (menu_id):
223|             '''Menu Command proxy.'''
224|             return lambda: menu_command(f'{menu_id}')
225| 
226|         # Create File Sub-Menu...
227|         mbarFile = tk.Menu(menubar, name='fileMenu', tearoff=0)
228|         mbarFile.add_command(label='New', command=proxy('New'))
229|         mbarFile.add_command(label='Open...', command=proxy('Open'))
230|         mbarFile.add_command(label='Save', command=proxy('Save'))
231|         mbarFile.add_command(label='Save As...', command=proxy('SaveAs'))
232|         mbarFile.add_separator()
233|         mbarFile.add_command(label='Exit', command=window_close)
234| 
235|         # Create Edit Sub-Menu...
236|         mbarEdit = tk.Menu(menubar, name='editMenu', tearoff=0)
237|         mbarEdit.add_command(label='Copy' , command=proxy('Copy'))
238|         mbarEdit.add_command(label='Paste', command=proxy('Paste'))
239| 
240|         # Create Help Sub-Menu...
241|         mbarHelp = tk.Menu(menubar, name='helpMenu', tearoff=0)
242|         mbarHelp.add_command(label='About', command=about)
243| 
244|         # Add sub-menus to MenuBar...
245|         menubar.add_cascade(label='File', menu=mbarFile, underline=0)
246|         menubar.add_cascade(label='Edit', menu=mbarEdit, underline=0)
247|         menubar.add_cascade(label='Help', menu=mbarHelp, underline=0)
248| 
249|         # Add menubar to main window...
250|         root.config(menu=menubar)
251| 
252|     # Open-The-Window thread starts here...
253|     root = tk.Tk()
254|     root.title(ttl)
255|     root.geometry(geo)
256|     root.bind('<Escape>', window_close)
257| 
258|     # Return root object...
259|     build_menubar()
260|     return root
261| 
262| 
263| if __name__ == '__main__':
264|     print()
265|     app = open_the_window()
266|     app.mainloop()
267|     print()
268| 
269| #:code::
270| import tkinter as tk
271| import tkinter.messagebox as msgbox
272| 
273| kwarg = lambda nm,dflt,typ,kw: typ(kw[nm]) if nm in kw else dflt
274| 
275| class BasicWindowApp:
276|     '''Simple Tk Window class.'''
277| 
278|     def __init__ (self, **kwargs):
279|         '''New BasicWindowApp instance.'''
280|         self.title = kwarg('title', 'The Window', str, kwargs)
281|         self.geom  = kwarg('geo', '480x240+300+100', str, kwargs)
282| 
283|         self.root = tk.Tk()
284|         self.root.title(self.title)
285|         self.root.geometry(self.geom)
286|         self.root.bind('<Escape>', self.app_exit)
287| 
288|         # Return root object...
289|         self._menubar()
290| 
291|     def command (self, command):
292|         '''Command handler.'''
293|         print(f'Command: {command}')
294| 
295|     def app_exit (self, *args):
296|         '''Close window.'''
297|         print('Exit App')
298|         self.root.destroy()
299| 
300|     def app_about (self, *args):
301|         '''About message box.'''
302|         msgbox.showinfo('About', 'Simple Tk Application.')
303| 
304|     def _menubar (self):
305|         ''' Create menubar.'''
306|         self.menubar = tk.Menu(self.root)
307| 
308|         def proxy (menu_id):
309|             '''Menu Command proxy.'''
310|             return lambda: self.command(f'M:{menu_id}')
311| 
312|         # Create File Sub-Menu...
313|         self.mbarFile = tk.Menu(self.menubar, name='fileMenu', tearoff=0)
314|         self.mbarFile.add_command(label='New', command=proxy('New'))
315|         self.mbarFile.add_command(label='Open...', command=proxy('Open'))
316|         self.mbarFile.add_command(label='Save', command=proxy('Save'))
317|         self.mbarFile.add_command(label='Save As...', command=proxy('SaveAs'))
318|         self.mbarFile.add_separator()
319|         self.mbarFile.add_command(label='Exit', command=self.app_exit)
320| 
321|         # Create Edit Sub-Menu...
322|         self.mbarEdit = tk.Menu(self.menubar, name='editMenu', tearoff=0)
323|         self.mbarEdit.add_command(label='Copy' , command=proxy('Copy'))
324|         self.mbarEdit.add_command(label='Paste', command=proxy('Paste'))
325| 
326|         # Create Help Sub-Menu...
327|         self.mbarHelp = tk.Menu(self.menubar, name='helpMenu', tearoff=0)
328|         self.mbarHelp.add_command(label='About', command=self.app_about)
329| 
330|         # Add sub-menus to MenuBar...
331|         self.menubar.add_cascade(label='File', menu=self.mbarFile, underline=0)
332|         self.menubar.add_cascade(label='Edit', menu=self.mbarEdit, underline=0)
333|         self.menubar.add_cascade(label='Help', menu=self.mbarHelp, underline=0)
334| 
335|         # Add menubar to main window...
336|         self.root.config(menu=self.menubar)
337| 
338|     def __repr__ (self):
339|         return f'<{type(self).__name__} @{id(self):08x}>'
340| 
341| 
342| if __name__ == '__main__':
343|     print()
344|     app = BasicWindowApp()
345|     print(app)
346|     app.root.mainloop()
347|     print()
348| 
349| #:code::
350| import tkinter as tk
351| import tkinter.messagebox as msgbox
352| 
353| kwarg = lambda nm,dflt,typ,kw: typ(kw[nm]) if nm in kw else dflt
354| 
355| class SimpleWindowApp:
356|     '''Simple Tk Window class.'''
357| 
358|     def __init__ (self, **kwargs):
359|         '''New BasicWindowApp instance.'''
360|         self.title = kwarg('title', 'The Window', str, kwargs)
361|         self.geom  = kwarg('geo', '480x240+300+100', str, kwargs)
362| 
363|         self.root = tk.Tk()
364|         self.root.title(self.title)
365|         self.root.geometry(self.geom)
366|         self.root.bind('<Escape>', self.app_exit)
367| 
368|         # Return root object...
369|         self._widgets()
370|         self._menubar()
371| 
372|     def command (self, cmd_id):
373|         '''Command handler.'''
374|         print(f'Command: {cmd_id}')
375|         if cmd_id.endswith('Exit'):
376|             self.app_exit()
377| 
378|     def app_exit (self, *args):
379|         '''Close window.'''
380|         print('Exit App')
381|         self.root.destroy()
382| 
383|     def app_about (self, *args):
384|         '''About message box.'''
385|         msgbox.showinfo('About', 'Simple Tk Application.')
386| 
387|     def _widgets (self):
388|         '''Create window widgets.'''
389|         self.wndw = tk.Frame(self.root, bg='#999999', relief='flat')
390|         self.wndw.pack(fill='both', expand=True, padx=4, pady=(0,4))
391| 
392|         self.lbl_top = tk.Label(self.wndw)
393|         self.lbl_top['text'] = 'Step by step, this app grows and grows!'
394|         self.lbl_top['bg'] = '#334455'
395|         self.lbl_top['fg'] = '#ffcc66'
396|         self.lbl_top['relief'] = 'raised'
397|         self.lbl_top['border'] = 2
398|         self.lbl_top['font'] = ('Arial', 12, 'bold')
399|         self.lbl_top.pack(side='top', fill='x', ipady=7)
400| 
401|         def proxy (button_id):
402|             '''Widgets Command proxy.'''
403|             return lambda: self.command(f'B:{button_id}')
404| 
405|         self.cmndbtns = tk.Frame(self.wndw)
406|         self.lbl_cmnds = tk.Label(self.cmndbtns, text='Commands:')
407|         self.lbl_cmnds.config(font=('Arial', 11, 'bold'), fg='#000099')
408| 
409|         props = lambda ix: dict(text=f'Run #{ix}', command=proxy(f'#{ix}'))
410|         self.btn_cmnd1 = tk.Button(self.cmndbtns, **props(1))
411|         self.btn_cmnd2 = tk.Button(self.cmndbtns, **props(2))
412|         self.btn_cmnd3 = tk.Button(self.cmndbtns, **props(3))
413|         self.btn_cmnd4 = tk.Button(self.cmndbtns, **props(4))
414|         self.btn_exit  = tk.Button(self.cmndbtns)
415|         self.btn_exit['text'] = text='Exit'
416|         self.btn_exit['command'] = proxy('Exit')
417| 
418|         self.lbl_cmnds.pack(side='left')
419|         self.btn_cmnd1.pack(side='left', padx=(10,0))
420|         self.btn_cmnd2.pack(side='left')
421|         self.btn_cmnd3.pack(side='left')
422|         self.btn_cmnd4.pack(side='left')
423|         self.btn_exit.pack(side='left', fill='x', expand=True)
424|         self.cmndbtns.pack(side='top', fill='x')
425| 
426|         self.apparea = tk.Frame(self.wndw, border=3)
427|         self.apparea.pack(side='top', fill='both', expand=True)
428|         self.apparea.config(bg='#336699', relief='sunken')
429| 
430|     def _menubar (self):
431|         ''' Create menubar.'''
432|         self.menubar = tk.Menu(self.root)
433| 
434|         def proxy (menu_id):
435|             '''Menu Command proxy.'''
436|             return lambda: self.command(f'M:{menu_id}')
437| 
438|         # Create File Sub-Menu...
439|         self.mbarFile = tk.Menu(self.menubar, name='fileMenu', tearoff=0)
440|         self.mbarFile.add_command(label='New', command=proxy('New'))
441|         self.mbarFile.add_command(label='Open...', command=proxy('Open'))
442|         self.mbarFile.add_command(label='Save', command=proxy('Save'))
443|         self.mbarFile.add_command(label='Save As...', command=proxy('SaveAs'))
444|         self.mbarFile.add_separator()
445|         self.mbarFile.add_command(label='Exit', command=proxy('Exit'))
446| 
447|         # Create Edit Sub-Menu...
448|         self.mbarEdit = tk.Menu(self.menubar, name='editMenu', tearoff=0)
449|         self.mbarEdit.add_command(label='Copy' , command=proxy('Copy'))
450|         self.mbarEdit.add_command(label='Paste', command=proxy('Paste'))
451| 
452|         # Create Help Sub-Menu...
453|         self.mbarHelp = tk.Menu(self.menubar, name='helpMenu', tearoff=0)
454|         self.mbarHelp.add_command(label='About', command=self.app_about)
455| 
456|         # Add sub-menus to MenuBar...
457|         self.menubar.add_cascade(label='File', menu=self.mbarFile)
458|         self.menubar.add_cascade(label='Edit', menu=self.mbarEdit)
459|         self.menubar.add_cascade(label='Help', menu=self.mbarHelp)
460| 
461|         # Add menubar to main window...
462|         self.root.config(menu=self.menubar)
463| 
464|     def __repr__ (self):
465|         return f'<{type(self).__name__} @{id(self):08x}>'
466| 
467| 
468| if __name__ == '__main__':
469|     print()
470|     app = SimpleWindowApp()
471|     print(app)
472|     app.root.mainloop()
473|     print()
474| 
475| #:code::
476| import tkinter as tk
477| 
478| # Create a window; set title; set geometry...
479| root = tk.Tk()
480| root.title('A Button-Test Window')
481| root.geometry('480x240+300+100')
482| 
483| # Create a button widget...
484| btn = tk.Button(root)
485| 
486| # Configure button...
487| btn['text'] = 'Click Me!'
488| btn['command'] = lambda: print('Click!')
489| 
490| # Map button to window...
491| btn.pack(anchor='nw')
492| 
493| #:code::
494| import tkinter as tk
495| 
496| # Create a window; set title; set geometry...
497| root = tk.Tk()
498| root.title('A Button-Test Window')
499| root.geometry('480x240+300+100')
500| 
501| # Create a button widget...
502| btn = tk.Button(root, text='Click Me!')
503| 
504| # Configure button...
505| btn.config(command= lambda: print('Click!'))
506| 
507| # Map button to window...
508| btn.pack(anchor='nw')
509| 
510| #:code::
511| import tkinter as tk
512| 
513| # Create a window; set title; set geometry...
514| root = tk.Tk()
515| root.title('A Button-Test Window')
516| root.geometry('480x240+300+100')
517| 
518| # Create a button widget...
519| btn = tk.Button(root)
520| 
521| # Configure button...
522| btn['text'] = 'Click Me!'
523| btn['command'] = lambda: print('Click!')
524| 
525| # Map button to window...
526| btn.grid(row=0, column=0, sticky='nesw')
527| 
528| #:code::
529| import tkinter as tk
530| 
531| # Create a window; set title; set geometry...
532| root = tk.Tk()
533| root.title('A Button-Test Window')
534| root.geometry('480x240+300+100')
535| 
536| # Create a button widget...
537| btn = tk.Button(root)
538| 
539| # Configure button...
540| btn['text'] = 'Click Me!'
541| btn['command'] = lambda: print('Click!')
542| 
543| # Map button to window...
544| btn.place(anchor='nw')
545| 
546| #:end:code::
547|