├── .gitattributes ├── .gitignore ├── Chapter01 └── Ch01_Code │ ├── First_GUI.py │ ├── GUI_add_label.py │ ├── GUI_adding_widgets_in_loop.py │ ├── GUI_checkbutton_widget.py │ ├── GUI_combobox_widget.py │ ├── GUI_combobox_widget_readonly.py │ ├── GUI_combobox_widget_readonly_plus_display_number.py │ ├── GUI_create_button_change_property.py │ ├── GUI_disable_button_widget.py │ ├── GUI_not_resizable.py │ ├── GUI_radiobutton_widget.py │ ├── GUI_scrolledtext_widget.py │ ├── GUI_set_focus.py │ ├── GUI_textbox_widget.py │ └── __init__.py ├── Chapter02 └── Ch02_Code │ ├── GUI_LabelFrame_column_one.py │ ├── GUI_LabelFrame_no_name.py │ ├── GUI_add_padding.py │ ├── GUI_add_padding_loop.py │ ├── GUI_arranging_labels.py │ ├── GUI_arranging_labels_vertical.py │ ├── GUI_embed_frames.py │ ├── GUI_embed_frames_align.py │ ├── GUI_embed_frames_align_entry_west.py │ ├── GUI_embed_frames_align_west.py │ ├── GUI_grid_layout.py │ ├── GUI_long_label.py │ ├── GUI_menubar_exit.py │ ├── GUI_menubar_exit_quit.py │ ├── GUI_menubar_file.py │ ├── GUI_menubar_help.py │ ├── GUI_menubar_separator.py │ ├── GUI_menubar_tearoff.py │ ├── GUI_remove_columnspan.py │ ├── GUI_remove_sticky.py │ ├── GUI_tabbed.py │ ├── GUI_tabbed_all_widgets.py │ ├── GUI_tabbed_all_widgets_both_tabs.py │ ├── GUI_tabbed_all_widgets_both_tabs_radio.py │ ├── GUI_tabbed_two.py │ ├── GUI_tabbed_two_mighty.py │ ├── GUI_tabbed_two_mighty_labels.py │ └── __init__.py ├── Chapter03 └── Ch03_Code │ ├── GUI_canvas.py │ ├── GUI_icon.py │ ├── GUI_independent_msg.py │ ├── GUI_independent_msg_info.py │ ├── GUI_independent_msg_one_window.py │ ├── GUI_independent_msg_one_window_title.py │ ├── GUI_message_box.py │ ├── GUI_message_box_error.py │ ├── GUI_message_box_warning.py │ ├── GUI_message_box_yes_no_cancel.py │ ├── GUI_progressbar.py │ ├── GUI_spinbox.py │ ├── GUI_spinbox_small.py │ ├── GUI_spinbox_small_bd.py │ ├── GUI_spinbox_small_bd_scrol.py │ ├── GUI_spinbox_small_bd_scrol_values.py │ ├── GUI_spinbox_two_ridge.py │ ├── GUI_spinbox_two_sunken.py │ ├── GUI_title.py │ ├── GUI_tooltip.py │ ├── __init__.py │ └── pyc.ico ├── Chapter04 └── Ch04_Code │ ├── GUI_OOP_2_classes.py │ ├── GUI_OOP_class_imported.py │ ├── GUI_OOP_class_imported_tooltip.py │ ├── GUI_PyDoubleVar_to_Float_Get.py │ ├── GUI_PyVar_Get.py │ ├── GUI_PyVar_defaults.py │ ├── GUI_StringVar.py │ ├── GUI_const_42.py │ ├── GUI_const_42_777.py │ ├── GUI_const_42_777_global.py │ ├── GUI_const_42_777_global_print.py │ ├── GUI_const_42_print.py │ ├── GUI_const_42_print_func.py │ ├── GUI_data_from_widget.py │ ├── ToolTip.py │ ├── __init__.py │ └── pyc.ico ├── Chapter05 └── Ch05_Code │ ├── Matplotlib_chart.py │ ├── Matplotlib_chart_with_legend.py │ ├── Matplotlib_chart_with_legend_missing_comma.py │ ├── Matplotlib_labels.py │ ├── Matplotlib_labels_four.py │ ├── Matplotlib_labels_two_charts.py │ ├── Matplotlib_labels_two_charts_not_scaled.py │ ├── Matplotlib_labels_two_charts_scaled.py │ ├── Matplotlib_labels_two_charts_scaled_dynamic.py │ ├── Matplotlib_labels_two_charts_scaled_dynamic_spike.py │ ├── Matplotlib_our_first_chart.py │ ├── Matplotlib_second_chart.py │ └── __init__.py ├── Chapter06 └── Ch06_Code │ ├── Backup │ └── GUI_copy_files.py │ ├── GUI_TCP_IP.py │ ├── GUI_URL.py │ ├── GUI_copy_files.py │ ├── GUI_copy_files_limit.py │ ├── GUI_multiple_threads.py │ ├── GUI_multiple_threads_sleep_freeze.py │ ├── GUI_multiple_threads_starting_a_thread.py │ ├── GUI_multiple_threads_stopping_a_thread.py │ ├── GUI_multiple_threads_thread_in_method.py │ ├── GUI_passing_queues.py │ ├── GUI_passing_queues_member.py │ ├── GUI_queues.py │ ├── GUI_queues_put_get.py │ ├── GUI_queues_put_get_loop.py │ ├── GUI_queues_put_get_loop_endless.py │ ├── GUI_queues_put_get_loop_endless_threaded.py │ ├── Queues.py │ ├── TCP_Server.py │ ├── ToolTip.py │ ├── URL.py │ ├── __init__.py │ └── pyc.ico ├── Chapter07 └── Ch07_Code │ ├── GUI_MySQL.py │ ├── GUI_MySQL_class.py │ ├── GuiDBConfig.py │ ├── MySQL_connect.py │ ├── MySQL_connect_import_dict.py │ ├── MySQL_connect_with_dict.py │ ├── MySQL_create_DB.py │ ├── MySQL_show_DBs.py │ ├── ToolTip.py │ ├── __init__.py │ └── pyc.ico ├── Chapter08 └── Ch08_Code │ ├── Callbacks_Refactored.py │ ├── GUI.py │ ├── GUI_Refactored.py │ ├── LanguageResources.py │ ├── Logger.py │ ├── ToolTip.py │ ├── UnitTests.py │ ├── UnitTestsEnglish.py │ ├── UnitTestsFail.py │ ├── UnitTestsMinimum.py │ ├── UnitTests_One.py │ ├── __init__.py │ ├── logs │ └── GUI_Refactored.log │ └── pyc.ico ├── Chapter09 └── Ch09_Code │ ├── Communicate.py │ ├── Control_Frameworks.py │ ├── Control_Frameworks_NOT_working.py │ ├── Embed_tkinter.py │ ├── Embed_wxPython.py │ ├── GUI_wxPython.py │ ├── Hello_wxPython.py │ ├── __init__.py │ ├── wxPython_frame_GUI.py │ └── wxPython_panel_GUI.py ├── Chapter10 └── Ch10_Code │ ├── OpenGL_SuperBible_Animation.py │ ├── OpenGL_SuperBible_Animation_with_stencil_NOT_working.py │ ├── OpenGL_SuperBible_Simple.py │ ├── OpenGL_SuperBible_Simple_Rectangle.py │ ├── Resources │ ├── Galaxy.gif │ ├── LightsInTheCity.gif │ ├── NothernLights.gif │ ├── Schloss_Neuschwarnstein.jpg │ ├── Sparkle.gif │ ├── Universe.jpg │ └── rivers expedition day.jpg │ ├── SlideShow.py │ ├── SlideShow_Pillow.py │ ├── SlideShow_try_jpg.py │ ├── Tile.bmp │ ├── __init__.py │ ├── import_OpenGL.py │ ├── import_OpenGL_cube_and_cone.py │ ├── pyglet_GUI.py │ ├── pyglet_GUI_Simple.py │ ├── wxPython_OpenGL_GUI.py │ ├── wxPython_Wallpaper.py │ └── wxPython_Wallpaper_simple.py ├── Chapter11 └── Ch11_Code │ ├── Folder1 │ └── Folder2 │ │ └── Folder3 │ │ └── MessageBox.py │ ├── GUI_Complexity_end_tab3.py │ ├── GUI_Complexity_end_tab3_multiple_notebooks.py │ ├── GUI_Complexity_start.py │ ├── GUI_Complexity_start_add_button.py │ ├── GUI_Complexity_start_add_three_more_buttons.py │ ├── GUI_Complexity_start_add_three_more_buttons_add_more.py │ ├── GUI_DesignPattern.py │ ├── GUI_FallDown.py │ ├── GUI_NOT_Spaghetti.py │ ├── GUI_Not_OOP.py │ ├── GUI_OOP.py │ ├── GUI_Spaghetti.py │ ├── GUI__init.py │ ├── GUI__init_import_folder.py │ ├── GUI__init_import_folder_directly.py │ ├── ToolTip.py │ ├── __init__.py │ └── pyc.ico ├── Instructions ├── LICENSE └── README.md /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Windows image file caches 2 | Thumbs.db 3 | ehthumbs.db 4 | 5 | # Folder config file 6 | Desktop.ini 7 | 8 | # Recycle Bin used on file shares 9 | $RECYCLE.BIN/ 10 | 11 | # Windows Installer files 12 | *.cab 13 | *.msi 14 | *.msm 15 | *.msp 16 | 17 | # Windows shortcuts 18 | *.lnk 19 | 20 | # ========================= 21 | # Operating System Files 22 | # ========================= 23 | 24 | # OSX 25 | # ========================= 26 | 27 | .DS_Store 28 | .AppleDouble 29 | .LSOverride 30 | 31 | # Thumbnails 32 | ._* 33 | 34 | # Files that might appear in the root of a volume 35 | .DocumentRevisions-V100 36 | .fseventsd 37 | .Spotlight-V100 38 | .TemporaryItems 39 | .Trashes 40 | .VolumeIcon.icns 41 | 42 | # Directories potentially created on remote AFP share 43 | .AppleDB 44 | .AppleDesktop 45 | Network Trash Folder 46 | Temporary Items 47 | .apdisk 48 | -------------------------------------------------------------------------------- /Chapter01/Ch01_Code/First_GUI.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | 10 | # Create instance 11 | win = tk.Tk() 12 | 13 | # Add a title 14 | win.title("Python GUI") 15 | 16 | #====================== 17 | # Start GUI 18 | #====================== 19 | win.mainloop() -------------------------------------------------------------------------------- /Chapter01/Ch01_Code/GUI_add_label.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | 11 | # Create instance 12 | win = tk.Tk() 13 | 14 | # Add a title 15 | win.title("Python GUI") 16 | 17 | # Adding a Label 18 | ttk.Label(win, text="A Label").grid(column=0, row=0) 19 | 20 | #====================== 21 | # Start GUI 22 | #====================== 23 | win.mainloop() -------------------------------------------------------------------------------- /Chapter01/Ch01_Code/GUI_adding_widgets_in_loop.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | from tkinter import scrolledtext 11 | 12 | # Create instance 13 | win = tk.Tk() 14 | 15 | # Add a title 16 | win.title("Python GUI") 17 | 18 | # Modify adding a Label 19 | a_label = ttk.Label(win, text="A Label") 20 | a_label.grid(column=0, row=0) 21 | 22 | # Modified Button Click Function 23 | def click_me(): 24 | action.configure(text='Hello ' + name.get() + ' ' + 25 | number_chosen.get()) 26 | 27 | # Changing our Label 28 | ttk.Label(win, text="Enter a name:").grid(column=0, row=0) 29 | 30 | # Adding a Textbox Entry widget 31 | name = tk.StringVar() 32 | name_entered = ttk.Entry(win, width=12, textvariable=name) 33 | name_entered.grid(column=0, row=1) 34 | 35 | # Adding a Button 36 | action = ttk.Button(win, text="Click Me!", command=click_me) 37 | action.grid(column=2, row=1) # <= change column to 2 38 | 39 | # Creating three checkbuttons 40 | ttk.Label(win, text="Choose a number:").grid(column=1, row=0) 41 | number = tk.StringVar() 42 | number_chosen = ttk.Combobox(win, width=12, textvariable=number, state='readonly') 43 | number_chosen['values'] = (1, 2, 4, 42, 100) 44 | number_chosen.grid(column=1, row=1) 45 | number_chosen.current(0) 46 | 47 | chVarDis = tk.IntVar() 48 | check1 = tk.Checkbutton(win, text="Disabled", variable=chVarDis, state='disabled') 49 | check1.select() 50 | check1.grid(column=0, row=4, sticky=tk.W) 51 | 52 | chVarUn = tk.IntVar() 53 | check2 = tk.Checkbutton(win, text="UnChecked", variable=chVarUn) 54 | check2.deselect() 55 | check2.grid(column=1, row=4, sticky=tk.W) 56 | 57 | chVarEn = tk.IntVar() 58 | check3 = tk.Checkbutton(win, text="Enabled", variable=chVarEn) 59 | check3.deselect() 60 | check3.grid(column=2, row=4, sticky=tk.W) 61 | 62 | # GUI Callback function 63 | def checkCallback(*ignoredArgs): 64 | # only enable one checkbutton 65 | if chVarUn.get(): check3.configure(state='disabled') 66 | else: check3.configure(state='normal') 67 | if chVarEn.get(): check2.configure(state='disabled') 68 | else: check2.configure(state='normal') 69 | 70 | # trace the state of the two checkbuttons 71 | chVarUn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 72 | chVarEn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 73 | 74 | 75 | # First, we change our Radiobutton global variables into a list 76 | colors = ["Blue", "Gold", "Red"] 77 | 78 | # We have also changed the callback function to be zero-based, using the list 79 | # instead of module-level global variables 80 | # Radiobutton Callback 81 | def radCall(): 82 | radSel=radVar.get() 83 | if radSel == 0: win.configure(background=colors[0]) # now zero-based 84 | elif radSel == 1: win.configure(background=colors[1]) # and using list 85 | elif radSel == 2: win.configure(background=colors[2]) 86 | 87 | # create three Radiobuttons using one variable 88 | radVar = tk.IntVar() 89 | 90 | # Next we are selecting a non-existing index value for radVar 91 | radVar.set(99) 92 | 93 | # Now we are creating all three Radiobutton widgets within one loop 94 | for col in range(3): 95 | curRad = tk.Radiobutton(win, text=colors[col], variable=radVar, 96 | value=col, command=radCall) 97 | curRad.grid(column=col, row=5, sticky=tk.W) 98 | 99 | # Using a scrolled Text control 100 | scrol_w = 30 101 | scrol_h = 3 102 | scr = scrolledtext.ScrolledText(win, width=scrol_w, height=scrol_h, wrap=tk.WORD) 103 | scr.grid(column=0, columnspan=3) 104 | 105 | name_entered.focus() # Place cursor into name Entry 106 | 107 | #====================== 108 | # Start GUI 109 | #====================== 110 | win.mainloop() -------------------------------------------------------------------------------- /Chapter01/Ch01_Code/GUI_checkbutton_widget.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | 11 | # Create instance 12 | win = tk.Tk() 13 | 14 | # Add a title 15 | win.title("Python GUI") 16 | 17 | # Modify adding a Label 18 | a_label = ttk.Label(win, text="A Label") 19 | a_label.grid(column=0, row=0) 20 | 21 | # Modified Button Click Function 22 | def click_me(): 23 | action.configure(text='Hello ' + name.get() + ' ' + 24 | number_chosen.get()) 25 | 26 | # Changing our Label 27 | ttk.Label(win, text="Enter a name:").grid(column=0, row=0) 28 | 29 | # Adding a Textbox Entry widget 30 | name = tk.StringVar() 31 | name_entered = ttk.Entry(win, width=12, textvariable=name) 32 | name_entered.grid(column=0, row=1) 33 | 34 | # Adding a Button 35 | action = ttk.Button(win, text="Click Me!", command=click_me) 36 | action.grid(column=2, row=1) 37 | 38 | # Creating three checkbuttons 39 | ttk.Label(win, text="Choose a number:").grid(column=1, row=0) 40 | number = tk.StringVar() 41 | number_chosen = ttk.Combobox(win, width=12, textvariable=number, state='readonly') 42 | number_chosen['values'] = (1, 2, 4, 42, 100) 43 | number_chosen.grid(column=1, row=1) 44 | number_chosen.current(0) 45 | 46 | chVarDis = tk.IntVar() 47 | check1 = tk.Checkbutton(win, text="Disabled", variable=chVarDis, state='disabled') 48 | check1.select() 49 | check1.grid(column=0, row=4, sticky=tk.W) 50 | 51 | chVarUn = tk.IntVar() 52 | check2 = tk.Checkbutton(win, text="UnChecked", variable=chVarUn) 53 | check2.deselect() 54 | check2.grid(column=1, row=4, sticky=tk.W) 55 | 56 | chVarEn = tk.IntVar() 57 | check3 = tk.Checkbutton(win, text="Enabled", variable=chVarEn) 58 | check3.select() 59 | check3.grid(column=2, row=4, sticky=tk.W) 60 | 61 | name_entered.focus() # Place cursor into name Entry 62 | #====================== 63 | # Start GUI 64 | #====================== 65 | win.mainloop() -------------------------------------------------------------------------------- /Chapter01/Ch01_Code/GUI_combobox_widget.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | 11 | # Create instance 12 | win = tk.Tk() 13 | 14 | # Add a title 15 | win.title("Python GUI") 16 | 17 | # Modify adding a Label 18 | a_label = ttk.Label(win, text="A Label") 19 | a_label.grid(column=0, row=0) 20 | 21 | # Modified Button Click Function 22 | def click_me(): 23 | action.configure(text='Hello ' + name.get()) 24 | # print(number) 25 | # print(number.get()) 26 | 27 | # Changing our Label 28 | ttk.Label(win, text="Enter a name:").grid(column=0, row=0) 29 | 30 | # Adding a Textbox Entry widget 31 | name = tk.StringVar() 32 | name_entered = ttk.Entry(win, width=12, textvariable=name) 33 | name_entered.grid(column=0, row=1) # column 0 34 | 35 | # Adding a Button 36 | action = ttk.Button(win, text="Click Me!", command=click_me) 37 | action.grid(column=2, row=1) # <= change column to 2 38 | 39 | ttk.Label(win, text="Choose a number:").grid(column=1, row=0) 40 | number = tk.StringVar() 41 | number_chosen = ttk.Combobox(win, width=12, textvariable=number) 42 | number_chosen['values'] = (1, 2, 4, 42, 100) 43 | number_chosen.grid(column=1, row=1) # <= Combobox in column 1 44 | number_chosen.current(0) 45 | 46 | name_entered.focus() # Place cursor into name Entry 47 | #====================== 48 | # Start GUI 49 | #====================== 50 | win.mainloop() -------------------------------------------------------------------------------- /Chapter01/Ch01_Code/GUI_combobox_widget_readonly.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | 11 | # Create instance 12 | win = tk.Tk() 13 | 14 | # Add a title 15 | win.title("Python GUI") 16 | 17 | # Modify adding a Label 18 | a_label = ttk.Label(win, text="A Label") 19 | a_label.grid(column=0, row=0) 20 | 21 | # Modified Button Click Function 22 | def click_me(): 23 | action.configure(text='Hello ' + name.get()) 24 | # print(number) 25 | # print(number.get()) 26 | 27 | # Changing our Label 28 | ttk.Label(win, text="Enter a name:").grid(column=0, row=0) 29 | 30 | # Adding a Textbox Entry widget 31 | name = tk.StringVar() 32 | name_entered = ttk.Entry(win, width=12, textvariable=name) 33 | name_entered.grid(column=0, row=1) 34 | 35 | # Adding a Button 36 | action = ttk.Button(win, text="Click Me!", command=click_me) 37 | action.grid(column=2, row=1) # <= change column to 2 38 | 39 | ttk.Label(win, text="Choose a number:").grid(column=1, row=0) 40 | number = tk.StringVar() 41 | number_chosen = ttk.Combobox(win, width=12, textvariable=number, state='readonly') 42 | number_chosen['values'] = (1, 2, 4, 42, 100) 43 | number_chosen.grid(column=1, row=1) 44 | number_chosen.current(0) 45 | 46 | name_entered.focus() # Place cursor into name Entry 47 | #====================== 48 | # Start GUI 49 | #====================== 50 | win.mainloop() -------------------------------------------------------------------------------- /Chapter01/Ch01_Code/GUI_combobox_widget_readonly_plus_display_number.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | 11 | # Create instance 12 | win = tk.Tk() 13 | 14 | # Add a title 15 | win.title("Python GUI") 16 | 17 | # Modify adding a Label 18 | a_label = ttk.Label(win, text="A Label") 19 | a_label.grid(column=0, row=0) 20 | 21 | # Modified Button Click Function 22 | def click_me(): 23 | action.configure(text='Hello ' + name.get() + ' ' + 24 | number_chosen.get()) 25 | 26 | # Changing our Label 27 | ttk.Label(win, text="Enter a name:").grid(column=0, row=0) 28 | 29 | # Adding a Textbox Entry widget 30 | name = tk.StringVar() 31 | name_entered = ttk.Entry(win, width=12, textvariable=name) 32 | name_entered.grid(column=0, row=1) 33 | 34 | # Adding a Button 35 | action = ttk.Button(win, text="Click Me!", command=click_me) 36 | action.grid(column=2, row=1) # <= change column to 2 37 | 38 | ttk.Label(win, text="Choose a number:").grid(column=1, row=0) 39 | number = tk.StringVar() 40 | number_chosen = ttk.Combobox(win, width=12, textvariable=number, state='readonly') 41 | number_chosen['values'] = (1, 2, 4, 42, 100) 42 | number_chosen.grid(column=1, row=1) 43 | number_chosen.current(0) 44 | 45 | name_entered.focus() # Place cursor into name Entry 46 | #====================== 47 | # Start GUI 48 | #====================== 49 | win.mainloop() -------------------------------------------------------------------------------- /Chapter01/Ch01_Code/GUI_create_button_change_property.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | 11 | # Create instance 12 | win = tk.Tk() 13 | 14 | # Add a title 15 | win.title("Python GUI") 16 | 17 | # Adding a Label that will get modified 18 | a_label = ttk.Label(win, text="A Label") 19 | a_label.grid(column=0, row=0) 20 | 21 | # Button Click Event Function 22 | def click_me(): 23 | action.configure(text="** I have been Clicked! **") 24 | a_label.configure(foreground='red') 25 | a_label.configure(text='A Red Label') 26 | 27 | # Adding a Button 28 | action = ttk.Button(win, text="Click Me!", command=click_me) 29 | action.grid(column=1, row=0) 30 | 31 | #====================== 32 | # Start GUI 33 | #====================== 34 | win.mainloop() -------------------------------------------------------------------------------- /Chapter01/Ch01_Code/GUI_disable_button_widget.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | 11 | # Create instance 12 | win = tk.Tk() 13 | 14 | # Add a title 15 | win.title("Python GUI") 16 | 17 | # Modify adding a Label 18 | a_label = ttk.Label(win, text="A Label") 19 | a_label.grid(column=0, row=0) 20 | 21 | # Modified Button Click Function 22 | def click_me(): 23 | action.configure(text='Hello ' + name.get()) 24 | 25 | # Changing our Label 26 | ttk.Label(win, text="Enter a name:").grid(column=0, row=0) 27 | 28 | # Adding a Textbox Entry widget 29 | name = tk.StringVar() 30 | name_entered = ttk.Entry(win, width=12, textvariable=name) 31 | name_entered.grid(column=0, row=1) 32 | 33 | # Adding a Button 34 | action = ttk.Button(win, text="Click Me!", command=click_me) 35 | action.grid(column=1, row=1) 36 | action.configure(state='disabled') # Disable the Button Widget 37 | 38 | name_entered.focus() # Place cursor into name Entry 39 | #====================== 40 | # Start GUI 41 | #====================== 42 | win.mainloop() -------------------------------------------------------------------------------- /Chapter01/Ch01_Code/GUI_not_resizable.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | 10 | # Create instance 11 | win = tk.Tk() 12 | 13 | # Add a title 14 | win.title("Python GUI") 15 | 16 | # Disable resizing the GUI by passing in False/False 17 | win.resizable(False, False) 18 | 19 | # Enable resizing x-dimension, disable y-dimension 20 | # win.resizable(True, False) 21 | 22 | #====================== 23 | # Start GUI 24 | #====================== 25 | win.mainloop() -------------------------------------------------------------------------------- /Chapter01/Ch01_Code/GUI_radiobutton_widget.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | 11 | # Create instance 12 | win = tk.Tk() 13 | 14 | # Add a title 15 | win.title("Python GUI") 16 | 17 | # Modify adding a Label 18 | a_label = ttk.Label(win, text="A Label") 19 | a_label.grid(column=0, row=0) 20 | 21 | # Modified Button Click Function 22 | def click_me(): 23 | action.configure(text='Hello ' + name.get() + ' ' + 24 | number_chosen.get()) 25 | 26 | # Changing our Label 27 | ttk.Label(win, text="Enter a name:").grid(column=0, row=0) 28 | 29 | # Adding a Textbox Entry widget 30 | name = tk.StringVar() 31 | name_entered = ttk.Entry(win, width=12, textvariable=name) 32 | name_entered.grid(column=0, row=1) 33 | 34 | # Adding a Button 35 | action = ttk.Button(win, text="Click Me!", command=click_me) 36 | action.grid(column=2, row=1) # <= change column to 2 37 | 38 | # Creating three checkbuttons 39 | ttk.Label(win, text="Choose a number:").grid(column=1, row=0) 40 | number = tk.StringVar() 41 | number_chosen = ttk.Combobox(win, width=12, textvariable=number, state='readonly') 42 | number_chosen['values'] = (1, 2, 4, 42, 100) 43 | number_chosen.grid(column=1, row=1) 44 | number_chosen.current(0) 45 | 46 | chVarDis = tk.IntVar() 47 | check1 = tk.Checkbutton(win, text="Disabled", variable=chVarDis, state='disabled') 48 | check1.select() 49 | check1.grid(column=0, row=4, sticky=tk.W) 50 | 51 | chVarUn = tk.IntVar() 52 | check2 = tk.Checkbutton(win, text="UnChecked", variable=chVarUn) 53 | check2.deselect() 54 | check2.grid(column=1, row=4, sticky=tk.W) 55 | 56 | chVarEn = tk.IntVar() 57 | check3 = tk.Checkbutton(win, text="Enabled", variable=chVarEn) 58 | check3.deselect() 59 | check3.grid(column=2, row=4, sticky=tk.W) 60 | 61 | # GUI Callback function 62 | def checkCallback(*ignoredArgs): 63 | # only enable one checkbutton 64 | if chVarUn.get(): check3.configure(state='disabled') 65 | else: check3.configure(state='normal') 66 | if chVarEn.get(): check2.configure(state='disabled') 67 | else: check2.configure(state='normal') 68 | 69 | # trace the state of the two checkbuttons 70 | chVarUn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 71 | chVarEn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 72 | 73 | # Radiobutton Globals 74 | COLOR1 = "Blue" 75 | COLOR2 = "Gold" 76 | COLOR3 = "Red" 77 | 78 | # Radiobutton Callback 79 | def radCall(): 80 | radSel=radVar.get() 81 | if radSel == 1: win.configure(background=COLOR1) 82 | elif radSel == 2: win.configure(background=COLOR2) 83 | elif radSel == 3: win.configure(background=COLOR3) 84 | 85 | # create three Radiobuttons using one variable 86 | radVar = tk.IntVar() 87 | 88 | rad1 = tk.Radiobutton(win, text=COLOR1, variable=radVar, value=1, command=radCall) 89 | rad1.grid(column=0, row=5, sticky=tk.W, columnspan=3) 90 | 91 | rad2 = tk.Radiobutton(win, text=COLOR2, variable=radVar, value=2, command=radCall) 92 | rad2.grid(column=1, row=5, sticky=tk.W, columnspan=3) 93 | 94 | rad3 = tk.Radiobutton(win, text=COLOR3, variable=radVar, value=3, command=radCall) 95 | rad3.grid(column=2, row=5, sticky=tk.W, columnspan=3) 96 | 97 | name_entered.focus() # Place cursor into name Entry 98 | #====================== 99 | # Start GUI 100 | #====================== 101 | win.mainloop() -------------------------------------------------------------------------------- /Chapter01/Ch01_Code/GUI_scrolledtext_widget.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | from tkinter import scrolledtext 11 | 12 | # Create instance 13 | win = tk.Tk() 14 | 15 | # Add a title 16 | win.title("Python GUI") 17 | 18 | # Modify adding a Label 19 | a_label = ttk.Label(win, text="A Label") 20 | a_label.grid(column=0, row=0) 21 | 22 | # Modified Button Click Function 23 | def click_me(): 24 | action.configure(text='Hello ' + name.get() + ' ' + 25 | number_chosen.get()) 26 | 27 | # Changing our Label 28 | ttk.Label(win, text="Enter a name:").grid(column=0, row=0) 29 | 30 | # Adding a Textbox Entry widget 31 | name = tk.StringVar() 32 | name_entered = ttk.Entry(win, width=12, textvariable=name) 33 | name_entered.grid(column=0, row=1) 34 | 35 | # Adding a Button 36 | action = ttk.Button(win, text="Click Me!", command=click_me) 37 | action.grid(column=2, row=1) # <= change column to 2 38 | 39 | # Creating three checkbuttons 40 | ttk.Label(win, text="Choose a number:").grid(column=1, row=0) 41 | number = tk.StringVar() 42 | number_chosen = ttk.Combobox(win, width=12, textvariable=number, state='readonly') 43 | number_chosen['values'] = (1, 2, 4, 42, 100) 44 | number_chosen.grid(column=1, row=1) 45 | number_chosen.current(0) 46 | 47 | chVarDis = tk.IntVar() 48 | check1 = tk.Checkbutton(win, text="Disabled", variable=chVarDis, state='disabled') 49 | check1.select() 50 | check1.grid(column=0, row=4, sticky=tk.W) 51 | 52 | chVarUn = tk.IntVar() 53 | check2 = tk.Checkbutton(win, text="UnChecked", variable=chVarUn) 54 | check2.deselect() 55 | check2.grid(column=1, row=4, sticky=tk.W) 56 | 57 | chVarEn = tk.IntVar() 58 | check3 = tk.Checkbutton(win, text="Enabled", variable=chVarEn) 59 | check3.deselect() 60 | check3.grid(column=2, row=4, sticky=tk.W) 61 | 62 | # GUI Callback function 63 | def checkCallback(*ignoredArgs): 64 | # only enable one checkbutton 65 | if chVarUn.get(): check3.configure(state='disabled') 66 | else: check3.configure(state='normal') 67 | if chVarEn.get(): check2.configure(state='disabled') 68 | else: check2.configure(state='normal') 69 | 70 | # trace the state of the two checkbuttons 71 | chVarUn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 72 | chVarEn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 73 | 74 | # Radiobutton Globals 75 | COLOR1 = "Blue" 76 | COLOR2 = "Gold" 77 | COLOR3 = "Red" 78 | 79 | # Radiobutton Callback 80 | def radCall(): 81 | radSel=radVar.get() 82 | if radSel == 1: win.configure(background=COLOR1) 83 | elif radSel == 2: win.configure(background=COLOR2) 84 | elif radSel == 3: win.configure(background=COLOR3) 85 | 86 | # create three Radiobuttons using one variable 87 | radVar = tk.IntVar() 88 | 89 | rad1 = tk.Radiobutton(win, text=COLOR1, variable=radVar, value=1, command=radCall) 90 | rad1.grid(column=0, row=5, sticky=tk.W, columnspan=3) 91 | 92 | rad2 = tk.Radiobutton(win, text=COLOR2, variable=radVar, value=2, command=radCall) 93 | rad2.grid(column=1, row=5, sticky=tk.W, columnspan=3) 94 | 95 | rad3 = tk.Radiobutton(win, text=COLOR3, variable=radVar, value=3, command=radCall) 96 | rad3.grid(column=2, row=5, sticky=tk.W, columnspan=3) 97 | 98 | # Using a scrolled Text control 99 | scrol_w = 30 100 | scrol_h = 3 101 | scr = scrolledtext.ScrolledText(win, width=scrol_w, height=scrol_h, wrap=tk.WORD) 102 | scr.grid(column=0, columnspan=3) 103 | 104 | name_entered.focus() # Place cursor into name Entry 105 | #====================== 106 | # Start GUI 107 | #====================== 108 | win.mainloop() -------------------------------------------------------------------------------- /Chapter01/Ch01_Code/GUI_set_focus.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | 11 | # Create instance 12 | win = tk.Tk() 13 | 14 | # Add a title 15 | win.title("Python GUI") 16 | 17 | # Modify adding a Label 18 | a_label = ttk.Label(win, text="A Label") 19 | a_label.grid(column=0, row=0) 20 | 21 | # Modified Button Click Function 22 | def click_me(): 23 | action.configure(text='Hello ' + name.get()) 24 | 25 | # Changing our Label 26 | ttk.Label(win, text="Enter a name:").grid(column=0, row=0) 27 | 28 | # Adding a Textbox Entry widget 29 | name = tk.StringVar() 30 | name_entered = ttk.Entry(win, width=12, textvariable=name) 31 | name_entered.grid(column=0, row=1) 32 | 33 | # Adding a Button 34 | action = ttk.Button(win, text="Click Me!", command=click_me) 35 | action.grid(column=1, row=1) 36 | 37 | name_entered.focus() # Place cursor into name Entry 38 | #====================== 39 | # Start GUI 40 | #====================== 41 | win.mainloop() -------------------------------------------------------------------------------- /Chapter01/Ch01_Code/GUI_textbox_widget.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | 11 | # Create instance 12 | win = tk.Tk() 13 | 14 | # Add a title 15 | win.title("Python GUI") 16 | 17 | # Modify adding a Label 18 | a_label = ttk.Label(win, text="A Label") 19 | a_label.grid(column=0, row=0) 20 | 21 | # Modified Button Click Function 22 | def click_me(): 23 | action.configure(text='Hello ' + name.get()) 24 | 25 | # Changing our Label 26 | ttk.Label(win, text="Enter a name:").grid(column=0, row=0) 27 | 28 | # Adding a Text box Entry widget 29 | name = tk.StringVar() 30 | name_entered = ttk.Entry(win, width=12, textvariable=name) 31 | name_entered.grid(column=0, row=1) 32 | 33 | # Adding a Button 34 | action = ttk.Button(win, text="Click Me!", command=click_me) 35 | action.grid(column=1, row=1) 36 | 37 | #====================== 38 | # Start GUI 39 | #====================== 40 | win.mainloop() -------------------------------------------------------------------------------- /Chapter01/Ch01_Code/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Python-GUI-Programming-Cookbook-Second-Edition/1ca9866be88b4191a5a951cbc4ead7aad903f226/Chapter01/Ch01_Code/__init__.py -------------------------------------------------------------------------------- /Chapter02/Ch02_Code/GUI_LabelFrame_column_one.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | from tkinter import scrolledtext 11 | 12 | # Create instance 13 | win = tk.Tk() 14 | 15 | # Add a title 16 | win.title("Python GUI") 17 | 18 | # Modify adding a Label 19 | a_label = ttk.Label(win, text="A Label") 20 | a_label.grid(column=0, row=0) 21 | 22 | # Modified Button Click Function 23 | def click_me(): 24 | action.configure(text='Hello ' + name.get() + ' ' + 25 | number_chosen.get()) 26 | 27 | # Changing our Label 28 | ttk.Label(win, text="Enter a name:").grid(column=0, row=0) 29 | 30 | # Adding a Textbox Entry widget 31 | name = tk.StringVar() 32 | name_entered = ttk.Entry(win, width=12, textvariable=name) 33 | name_entered.grid(column=0, row=1) 34 | 35 | # Adding a Button 36 | action = ttk.Button(win, text="Click Me!", command=click_me) 37 | action.grid(column=2, row=1) # <= change column to 2 38 | 39 | # Creating three checkbuttons 40 | ttk.Label(win, text="Choose a number:").grid(column=1, row=0) 41 | number = tk.StringVar() 42 | number_chosen = ttk.Combobox(win, width=12, textvariable=number, state='readonly') 43 | number_chosen['values'] = (1, 2, 4, 42, 100) 44 | number_chosen.grid(column=1, row=1) 45 | number_chosen.current(0) 46 | 47 | chVarDis = tk.IntVar() 48 | check1 = tk.Checkbutton(win, text="Disabled", variable=chVarDis, state='disabled') 49 | check1.select() 50 | check1.grid(column=0, row=4, sticky=tk.W) 51 | 52 | chVarUn = tk.IntVar() 53 | check2 = tk.Checkbutton(win, text="UnChecked", variable=chVarUn) 54 | check2.deselect() 55 | check2.grid(column=1, row=4, sticky=tk.W) 56 | 57 | chVarEn = tk.IntVar() 58 | check3 = tk.Checkbutton(win, text="Enabled", variable=chVarEn) 59 | check3.deselect() 60 | check3.grid(column=2, row=4, sticky=tk.W) 61 | 62 | # GUI Callback function 63 | def checkCallback(*ignoredArgs): 64 | # only enable one checkbutton 65 | if chVarUn.get(): check3.configure(state='disabled') 66 | else: check3.configure(state='normal') 67 | if chVarEn.get(): check2.configure(state='disabled') 68 | else: check2.configure(state='normal') 69 | 70 | # trace the state of the two checkbuttons 71 | chVarUn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 72 | chVarEn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 73 | 74 | 75 | # Using a scrolled Text control 76 | scrol_w = 30 77 | scrol_h = 3 78 | scr = scrolledtext.ScrolledText(win, width=scrol_w, height=scrol_h, wrap=tk.WORD) 79 | #### scr.grid(column=0, row=5, sticky='WE', columnspan=3) 80 | scr.grid(column=0, row=5, columnspan=3) # sticky property removed 81 | 82 | 83 | # First, we change our Radiobutton global variables into a list 84 | colors = ["Blue", "Gold", "Red"] 85 | 86 | # We have also changed the callback function to be zero-based, using the list 87 | # instead of module-level global variables 88 | # Radiobutton Callback 89 | def radCall(): 90 | radSel=radVar.get() 91 | if radSel == 0: win.configure(background=colors[0]) # zero-based 92 | elif radSel == 1: win.configure(background=colors[1]) # using list 93 | elif radSel == 2: win.configure(background=colors[2]) 94 | 95 | # create three Radiobuttons using one variable 96 | radVar = tk.IntVar() 97 | 98 | # Next we are selecting a non-existing index value for radVar 99 | radVar.set(99) 100 | 101 | # Now we are creating all three Radiobutton widgets within one loop 102 | for col in range(3): 103 | curRad = tk.Radiobutton(win, text=colors[col], variable=radVar, 104 | value=col, command=radCall) 105 | curRad.grid(column=col, row=6, sticky=tk.W) # row=6 106 | 107 | # Create a container to hold labels 108 | buttons_frame = ttk.LabelFrame(win, text=' Labels in a Frame ') 109 | buttons_frame.grid(column=0, row=7) 110 | # buttons_frame.grid(column=1, row=7) # now in col 1 111 | 112 | # Place labels into the container element 113 | ttk.Label(buttons_frame, text="Label1").grid(column=0, row=0, sticky=tk.W) 114 | ttk.Label(buttons_frame, text="Label2").grid(column=1, row=0, sticky=tk.W) 115 | ttk.Label(buttons_frame, text="Label3").grid(column=2, row=0, sticky=tk.W) 116 | 117 | name_entered.focus() # Place cursor into name Entry 118 | #====================== 119 | # Start GUI 120 | #====================== 121 | win.mainloop() -------------------------------------------------------------------------------- /Chapter02/Ch02_Code/GUI_LabelFrame_no_name.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | from tkinter import scrolledtext 11 | 12 | # Create instance 13 | win = tk.Tk() 14 | 15 | # Add a title 16 | win.title("Python GUI") 17 | 18 | # Modify adding a Label 19 | a_label = ttk.Label(win, text="A Label") 20 | a_label.grid(column=0, row=0) 21 | 22 | # Modified Button Click Function 23 | def click_me(): 24 | action.configure(text='Hello ' + name.get() + ' ' + 25 | number_chosen.get()) 26 | 27 | # Changing our Label 28 | ttk.Label(win, text="Enter a name:").grid(column=0, row=0) 29 | 30 | # Adding a Textbox Entry widget 31 | name = tk.StringVar() 32 | name_entered = ttk.Entry(win, width=12, textvariable=name) 33 | name_entered.grid(column=0, row=1) 34 | 35 | # Adding a Button 36 | action = ttk.Button(win, text="Click Me!", command=click_me) 37 | action.grid(column=2, row=1) # <= change column to 2 38 | 39 | # Creating three checkbuttons 40 | ttk.Label(win, text="Choose a number:").grid(column=1, row=0) 41 | number = tk.StringVar() 42 | number_chosen = ttk.Combobox(win, width=12, textvariable=number, state='readonly') 43 | number_chosen['values'] = (1, 2, 4, 42, 100) 44 | number_chosen.grid(column=1, row=1) 45 | number_chosen.current(0) 46 | 47 | chVarDis = tk.IntVar() 48 | check1 = tk.Checkbutton(win, text="Disabled", variable=chVarDis, state='disabled') 49 | check1.select() 50 | check1.grid(column=0, row=4, sticky=tk.W) 51 | 52 | chVarUn = tk.IntVar() 53 | check2 = tk.Checkbutton(win, text="UnChecked", variable=chVarUn) 54 | check2.deselect() 55 | check2.grid(column=1, row=4, sticky=tk.W) 56 | 57 | chVarEn = tk.IntVar() 58 | check3 = tk.Checkbutton(win, text="Enabled", variable=chVarEn) 59 | check3.deselect() 60 | check3.grid(column=2, row=4, sticky=tk.W) 61 | 62 | # GUI Callback function 63 | def checkCallback(*ignoredArgs): 64 | # only enable one checkbutton 65 | if chVarUn.get(): check3.configure(state='disabled') 66 | else: check3.configure(state='normal') 67 | if chVarEn.get(): check2.configure(state='disabled') 68 | else: check2.configure(state='normal') 69 | 70 | # trace the state of the two checkbuttons 71 | chVarUn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 72 | chVarEn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 73 | 74 | 75 | # Using a scrolled Text control 76 | scrol_w = 30 77 | scrol_h = 3 78 | scr = scrolledtext.ScrolledText(win, width=scrol_w, height=scrol_h, wrap=tk.WORD) 79 | scr.grid(column=0, row=5, sticky='WE', columnspan=3) # row=5 80 | 81 | # First, we change our Radiobutton global variables into a list 82 | colors = ["Blue", "Gold", "Red"] 83 | 84 | # We have also changed the callback function to be zero-based, using the list 85 | # instead of module-level global variables 86 | # Radiobutton Callback 87 | def radCall(): 88 | radSel=radVar.get() 89 | if radSel == 0: win.configure(background=colors[0]) # zero-based 90 | elif radSel == 1: win.configure(background=colors[1]) # using list 91 | elif radSel == 2: win.configure(background=colors[2]) 92 | 93 | # create three Radiobuttons using one variable 94 | radVar = tk.IntVar() 95 | 96 | # Next we are selecting a non-existing index value for radVar 97 | radVar.set(99) 98 | 99 | # Now we are creating all three Radiobutton widgets within one loop 100 | for col in range(3): 101 | curRad = tk.Radiobutton(win, text=colors[col], variable=radVar, 102 | value=col, command=radCall) 103 | curRad.grid(column=col, row=6, sticky=tk.W) # row=6 104 | # Create a container to hold labels 105 | # buttons_frame = ttk.LabelFrame(win, text=' Labels in a Frame ') 106 | # buttons_frame.grid(column=0, row=7, padx=20, pady=40) 107 | 108 | buttons_frame = ttk.LabelFrame(win, text='') # no LabelFrame name 109 | buttons_frame.grid(column=0, row=7) 110 | 111 | # buttons_frame.grid(column=1, row=7) # now in col 1 112 | 113 | # Place labels into the container element 114 | ttk.Label(buttons_frame, text="Label1").grid(column=0, row=0) 115 | ttk.Label(buttons_frame, text="Label2").grid(column=0, row=1) 116 | ttk.Label(buttons_frame, text="Label3").grid(column=0, row=2) 117 | 118 | for child in buttons_frame.winfo_children(): 119 | child.grid_configure(padx=8, pady=4) 120 | 121 | name_entered.focus() # Place cursor into name Entry 122 | #====================== 123 | # Start GUI 124 | #====================== 125 | win.mainloop() 126 | -------------------------------------------------------------------------------- /Chapter02/Ch02_Code/GUI_add_padding.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | from tkinter import scrolledtext 11 | 12 | # Create instance 13 | win = tk.Tk() 14 | 15 | # Add a title 16 | win.title("Python GUI") 17 | 18 | # Modify adding a Label 19 | a_label = ttk.Label(win, text="A Label") 20 | a_label.grid(column=0, row=0) 21 | 22 | # Modified Button Click Function 23 | def click_me(): 24 | action.configure(text='Hello ' + name.get() + ' ' + 25 | number_chosen.get()) 26 | 27 | # Changing our Label 28 | ttk.Label(win, text="Enter a name:").grid(column=0, row=0) 29 | 30 | # Adding a Textbox Entry widget 31 | name = tk.StringVar() 32 | name_entered = ttk.Entry(win, width=12, textvariable=name) 33 | name_entered.grid(column=0, row=1) 34 | 35 | # Adding a Button 36 | action = ttk.Button(win, text="Click Me!", command=click_me) 37 | action.grid(column=2, row=1) # <= change column to 2 38 | 39 | # Creating three checkbuttons 40 | ttk.Label(win, text="Choose a number:").grid(column=1, row=0) 41 | number = tk.StringVar() 42 | number_chosen = ttk.Combobox(win, width=12, textvariable=number, state='readonly') 43 | number_chosen['values'] = (1, 2, 4, 42, 100) 44 | number_chosen.grid(column=1, row=1) 45 | number_chosen.current(0) 46 | 47 | chVarDis = tk.IntVar() 48 | check1 = tk.Checkbutton(win, text="Disabled", variable=chVarDis, state='disabled') 49 | check1.select() 50 | check1.grid(column=0, row=4, sticky=tk.W) 51 | 52 | chVarUn = tk.IntVar() 53 | check2 = tk.Checkbutton(win, text="UnChecked", variable=chVarUn) 54 | check2.deselect() 55 | check2.grid(column=1, row=4, sticky=tk.W) 56 | 57 | chVarEn = tk.IntVar() 58 | check3 = tk.Checkbutton(win, text="Enabled", variable=chVarEn) 59 | check3.deselect() 60 | check3.grid(column=2, row=4, sticky=tk.W) 61 | 62 | # GUI Callback function 63 | def checkCallback(*ignoredArgs): 64 | # only enable one checkbutton 65 | if chVarUn.get(): check3.configure(state='disabled') 66 | else: check3.configure(state='normal') 67 | if chVarEn.get(): check2.configure(state='disabled') 68 | else: check2.configure(state='normal') 69 | 70 | # trace the state of the two checkbuttons 71 | chVarUn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 72 | chVarEn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 73 | 74 | 75 | # Using a scrolled Text control 76 | scrol_w = 30 77 | scrol_h = 3 78 | scr = scrolledtext.ScrolledText(win, width=scrol_w, height=scrol_h, wrap=tk.WORD) 79 | scr.grid(column=0, row=5, sticky='WE', columnspan=3) # now row=5 80 | 81 | # First, we change our Radiobutton global variables into a list 82 | colors = ["Blue", "Gold", "Red"] 83 | 84 | # We have also changed the callback function to be zero-based, using the list 85 | # instead of module-level global variables 86 | # Radiobutton Callback 87 | def radCall(): 88 | radSel=radVar.get() 89 | if radSel == 0: win.configure(background=colors[0]) # now zero-based 90 | elif radSel == 1: win.configure(background=colors[1]) # and using list 91 | elif radSel == 2: win.configure(background=colors[2]) 92 | 93 | # create three Radiobuttons using one variable 94 | radVar = tk.IntVar() 95 | 96 | # Next we are selecting a non-existing index value for radVar 97 | radVar.set(99) 98 | 99 | # Now we are creating all three Radiobutton widgets within one loop 100 | for col in range(3): 101 | curRad = tk.Radiobutton(win, text=colors[col], variable=radVar, 102 | value=col, command=radCall) 103 | curRad.grid(column=col, row=6, sticky=tk.W) # now row=6 104 | 105 | # Create a container to hold labels 106 | buttons_frame = ttk.LabelFrame(win, text=' Labels in a Frame ') 107 | buttons_frame.grid(column=0, row=7, padx=20, pady=40) # padx, pady 108 | 109 | # Place labels into the container element - vertically 110 | ttk.Label(buttons_frame, text="Label1").grid(column=0, row=0) 111 | ttk.Label(buttons_frame, text="Label2").grid(column=0, row=1) 112 | ttk.Label(buttons_frame, text="Label3").grid(column=0, row=2) 113 | 114 | name_entered.focus() # Place cursor into name Entry 115 | #====================== 116 | # Start GUI 117 | #====================== 118 | win.mainloop() 119 | -------------------------------------------------------------------------------- /Chapter02/Ch02_Code/GUI_add_padding_loop.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | from tkinter import scrolledtext 11 | 12 | # Create instance 13 | win = tk.Tk() 14 | 15 | # Add a title 16 | win.title("Python GUI") 17 | 18 | # Modify adding a Label 19 | a_label = ttk.Label(win, text="A Label") 20 | a_label.grid(column=0, row=0) 21 | 22 | # Modified Button Click Function 23 | def click_me(): 24 | action.configure(text='Hello ' + name.get() + ' ' + 25 | number_chosen.get()) 26 | 27 | # Changing our Label 28 | ttk.Label(win, text="Enter a name:").grid(column=0, row=0) 29 | 30 | # Adding a Textbox Entry widget 31 | name = tk.StringVar() 32 | name_entered = ttk.Entry(win, width=12, textvariable=name) 33 | name_entered.grid(column=0, row=1) 34 | 35 | # Adding a Button 36 | action = ttk.Button(win, text="Click Me!", command=click_me) 37 | action.grid(column=2, row=1) # <= change column to 2 38 | 39 | # Creating three checkbuttons 40 | ttk.Label(win, text="Choose a number:").grid(column=1, row=0) 41 | number = tk.StringVar() 42 | number_chosen = ttk.Combobox(win, width=12, textvariable=number, state='readonly') 43 | number_chosen['values'] = (1, 2, 4, 42, 100) 44 | number_chosen.grid(column=1, row=1) 45 | number_chosen.current(0) 46 | 47 | chVarDis = tk.IntVar() 48 | check1 = tk.Checkbutton(win, text="Disabled", variable=chVarDis, state='disabled') 49 | check1.select() 50 | check1.grid(column=0, row=4, sticky=tk.W) 51 | 52 | chVarUn = tk.IntVar() 53 | check2 = tk.Checkbutton(win, text="UnChecked", variable=chVarUn) 54 | check2.deselect() 55 | check2.grid(column=1, row=4, sticky=tk.W) 56 | 57 | chVarEn = tk.IntVar() 58 | check3 = tk.Checkbutton(win, text="Enabled", variable=chVarEn) 59 | check3.deselect() 60 | check3.grid(column=2, row=4, sticky=tk.W) 61 | 62 | # GUI Callback function 63 | def checkCallback(*ignoredArgs): 64 | # only enable one checkbutton 65 | if chVarUn.get(): check3.configure(state='disabled') 66 | else: check3.configure(state='normal') 67 | if chVarEn.get(): check2.configure(state='disabled') 68 | else: check2.configure(state='normal') 69 | 70 | # trace the state of the two checkbuttons 71 | chVarUn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 72 | chVarEn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 73 | 74 | 75 | # Using a scrolled Text control 76 | scrol_w = 30 77 | scrol_h = 3 78 | scr = scrolledtext.ScrolledText(win, width=scrol_w, height=scrol_h, wrap=tk.WORD) 79 | scr.grid(column=0, row=5, sticky='WE', columnspan=3) # now row=5 80 | 81 | # First, we change our Radiobutton global variables into a list 82 | colors = ["Blue", "Gold", "Red"] 83 | 84 | # We have also changed the callback function to be zero-based, using the list 85 | # instead of module-level global variables 86 | # Radiobutton Callback 87 | def radCall(): 88 | radSel=radVar.get() 89 | if radSel == 0: win.configure(background=colors[0]) # now zero-based 90 | elif radSel == 1: win.configure(background=colors[1]) # and using list 91 | elif radSel == 2: win.configure(background=colors[2]) 92 | 93 | # create three Radiobuttons using one variable 94 | radVar = tk.IntVar() 95 | 96 | # Next we are selecting a non-existing index value for radVar 97 | radVar.set(99) 98 | 99 | # Now we are creating all three Radiobutton widgets within one loop 100 | for col in range(3): 101 | curRad = tk.Radiobutton(win, text=colors[col], variable=radVar, 102 | value=col, command=radCall) 103 | curRad.grid(column=col, row=6, sticky=tk.W) # now row=6 104 | 105 | # Create a container to hold labels 106 | buttons_frame = ttk.LabelFrame(win, text=' Labels in a Frame ') 107 | buttons_frame.grid(column=0, row=7, padx=20, pady=40) # padx, pady 108 | 109 | # Place labels into the container element - vertically 110 | ttk.Label(buttons_frame, text="Label1").grid(column=0, row=0) 111 | ttk.Label(buttons_frame, text="Label2").grid(column=0, row=1) 112 | ttk.Label(buttons_frame, text="Label3").grid(column=0, row=2) 113 | 114 | for child in buttons_frame.winfo_children(): 115 | child.grid_configure(padx=8, pady=4) 116 | 117 | 118 | name_entered.focus() # Place cursor into name Entry 119 | #====================== 120 | # Start GUI 121 | #====================== 122 | win.mainloop() 123 | -------------------------------------------------------------------------------- /Chapter02/Ch02_Code/GUI_arranging_labels.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | from tkinter import scrolledtext 11 | 12 | # Create instance 13 | win = tk.Tk() 14 | 15 | # Add a title 16 | win.title("Python GUI") 17 | 18 | # Modify adding a Label 19 | a_label = ttk.Label(win, text="A Label") 20 | a_label.grid(column=0, row=0) 21 | 22 | # Modified Button Click Function 23 | def click_me(): 24 | action.configure(text='Hello ' + name.get() + ' ' + 25 | number_chosen.get()) 26 | 27 | # Changing our Label 28 | ttk.Label(win, text="Enter a name:").grid(column=0, row=0) 29 | 30 | # Adding a Textbox Entry widget 31 | name = tk.StringVar() 32 | name_entered = ttk.Entry(win, width=12, textvariable=name) 33 | name_entered.grid(column=0, row=1) 34 | 35 | # Adding a Button 36 | action = ttk.Button(win, text="Click Me!", command=click_me) 37 | action.grid(column=2, row=1) # <= change column to 2 38 | 39 | # Creating three checkbuttons 40 | ttk.Label(win, text="Choose a number:").grid(column=1, row=0) 41 | number = tk.StringVar() 42 | number_chosen = ttk.Combobox(win, width=12, textvariable=number, state='readonly') 43 | number_chosen['values'] = (1, 2, 4, 42, 100) 44 | number_chosen.grid(column=1, row=1) 45 | number_chosen.current(0) 46 | 47 | chVarDis = tk.IntVar() 48 | check1 = tk.Checkbutton(win, text="Disabled", variable=chVarDis, state='disabled') 49 | check1.select() 50 | check1.grid(column=0, row=4, sticky=tk.W) 51 | 52 | chVarUn = tk.IntVar() 53 | check2 = tk.Checkbutton(win, text="UnChecked", variable=chVarUn) 54 | check2.deselect() 55 | check2.grid(column=1, row=4, sticky=tk.W) 56 | 57 | chVarEn = tk.IntVar() 58 | check3 = tk.Checkbutton(win, text="Enabled", variable=chVarEn) 59 | check3.deselect() 60 | check3.grid(column=2, row=4, sticky=tk.W) 61 | 62 | # GUI Callback function 63 | def checkCallback(*ignoredArgs): 64 | # only enable one checkbutton 65 | if chVarUn.get(): check3.configure(state='disabled') 66 | else: check3.configure(state='normal') 67 | if chVarEn.get(): check2.configure(state='disabled') 68 | else: check2.configure(state='normal') 69 | 70 | # trace the state of the two checkbuttons 71 | chVarUn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 72 | chVarEn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 73 | 74 | 75 | # Using a scrolled Text control 76 | scrol_w = 30 77 | scrol_h = 3 78 | scr = scrolledtext.ScrolledText(win, width=scrol_w, height=scrol_h, wrap=tk.WORD) 79 | scr.grid(column=0, row=5, sticky='WE', columnspan=3) # now row=5 80 | 81 | # First, we change our Radiobutton global variables into a list 82 | colors = ["Blue", "Gold", "Red"] 83 | 84 | # We have also changed the callback function to be zero-based, using the list 85 | # instead of module-level global variables 86 | # Radiobutton Callback 87 | def radCall(): 88 | radSel=radVar.get() 89 | if radSel == 0: win.configure(background=colors[0]) # now zero-based 90 | elif radSel == 1: win.configure(background=colors[1]) # and using list 91 | elif radSel == 2: win.configure(background=colors[2]) 92 | 93 | # create three Radiobuttons using one variable 94 | radVar = tk.IntVar() 95 | 96 | # Next we are selecting a non-existing index value for radVar 97 | radVar.set(99) 98 | 99 | # Now we are creating all three Radiobutton widgets within one loop 100 | for col in range(3): 101 | curRad = tk.Radiobutton(win, text=colors[col], variable=radVar, 102 | value=col, command=radCall) 103 | curRad.grid(column=col, row=6, sticky=tk.W) # now row=6 104 | 105 | # Create a container to hold labels 106 | buttons_frame = ttk.LabelFrame(win, text=' Labels in a Frame ') 107 | buttons_frame.grid(column=0, row=7) 108 | 109 | # Place labels into the container element 110 | ttk.Label(buttons_frame, text="Label1").grid(column=0, row=0, sticky=tk.W) 111 | ttk.Label(buttons_frame, text="Label2").grid(column=1, row=0, sticky=tk.W) 112 | ttk.Label(buttons_frame, text="Label3").grid(column=2, row=0, sticky=tk.W) 113 | 114 | name_entered.focus() # Place cursor into name Entry 115 | #====================== 116 | # Start GUI 117 | #====================== 118 | win.mainloop() -------------------------------------------------------------------------------- /Chapter02/Ch02_Code/GUI_arranging_labels_vertical.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | from tkinter import scrolledtext 11 | 12 | # Create instance 13 | win = tk.Tk() 14 | 15 | # Add a title 16 | win.title("Python GUI") 17 | 18 | # Modify adding a Label 19 | a_label = ttk.Label(win, text="A Label") 20 | a_label.grid(column=0, row=0) 21 | 22 | # Modified Button Click Function 23 | def click_me(): 24 | action.configure(text='Hello ' + name.get() + ' ' + 25 | number_chosen.get()) 26 | 27 | # Changing our Label 28 | ttk.Label(win, text="Enter a name:").grid(column=0, row=0) 29 | 30 | # Adding a Textbox Entry widget 31 | name = tk.StringVar() 32 | name_entered = ttk.Entry(win, width=12, textvariable=name) 33 | name_entered.grid(column=0, row=1) 34 | 35 | # Adding a Button 36 | action = ttk.Button(win, text="Click Me!", command=click_me) 37 | action.grid(column=2, row=1) # <= change column to 2 38 | 39 | # Creating three checkbuttons 40 | ttk.Label(win, text="Choose a number:").grid(column=1, row=0) 41 | number = tk.StringVar() 42 | number_chosen = ttk.Combobox(win, width=12, textvariable=number, state='readonly') 43 | number_chosen['values'] = (1, 2, 4, 42, 100) 44 | number_chosen.grid(column=1, row=1) 45 | number_chosen.current(0) 46 | 47 | chVarDis = tk.IntVar() 48 | check1 = tk.Checkbutton(win, text="Disabled", variable=chVarDis, state='disabled') 49 | check1.select() 50 | check1.grid(column=0, row=4, sticky=tk.W) 51 | 52 | chVarUn = tk.IntVar() 53 | check2 = tk.Checkbutton(win, text="UnChecked", variable=chVarUn) 54 | check2.deselect() 55 | check2.grid(column=1, row=4, sticky=tk.W) 56 | 57 | chVarEn = tk.IntVar() 58 | check3 = tk.Checkbutton(win, text="Enabled", variable=chVarEn) 59 | check3.deselect() 60 | check3.grid(column=2, row=4, sticky=tk.W) 61 | 62 | # GUI Callback function 63 | def checkCallback(*ignoredArgs): 64 | # only enable one checkbutton 65 | if chVarUn.get(): check3.configure(state='disabled') 66 | else: check3.configure(state='normal') 67 | if chVarEn.get(): check2.configure(state='disabled') 68 | else: check2.configure(state='normal') 69 | 70 | # trace the state of the two checkbuttons 71 | chVarUn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 72 | chVarEn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 73 | 74 | 75 | # Using a scrolled Text control 76 | scrol_w = 30 77 | scrol_h = 3 78 | scr = scrolledtext.ScrolledText(win, width=scrol_w, height=scrol_h, wrap=tk.WORD) 79 | scr.grid(column=0, row=5, sticky='WE', columnspan=3) # now row=5 80 | 81 | # First, we change our Radiobutton global variables into a list 82 | colors = ["Blue", "Gold", "Red"] 83 | 84 | # We have also changed the callback function to be zero-based, using the list 85 | # instead of module-level global variables 86 | # Radiobutton Callback 87 | def radCall(): 88 | radSel=radVar.get() 89 | if radSel == 0: win.configure(background=colors[0]) # now zero-based 90 | elif radSel == 1: win.configure(background=colors[1]) # and using list 91 | elif radSel == 2: win.configure(background=colors[2]) 92 | 93 | # create three Radiobuttons using one variable 94 | radVar = tk.IntVar() 95 | 96 | # Next we are selecting a non-existing index value for radVar 97 | radVar.set(99) 98 | 99 | # Now we are creating all three Radiobutton widgets within one loop 100 | for col in range(3): 101 | curRad = tk.Radiobutton(win, text=colors[col], variable=radVar, 102 | value=col, command=radCall) 103 | curRad.grid(column=col, row=6, sticky=tk.W) # now row=6 104 | 105 | # Create a container to hold labels 106 | buttons_frame = ttk.LabelFrame(win, text=' Labels in a Frame ') 107 | buttons_frame.grid(column=0, row=7) 108 | 109 | # Place labels into the container element - vertically 110 | ttk.Label(buttons_frame, text="Label1").grid(column=0, row=0) 111 | ttk.Label(buttons_frame, text="Label2").grid(column=0, row=1) 112 | ttk.Label(buttons_frame, text="Label3").grid(column=0, row=2) 113 | 114 | name_entered.focus() # Place cursor into name Entry 115 | #====================== 116 | # Start GUI 117 | #====================== 118 | win.mainloop() 119 | -------------------------------------------------------------------------------- /Chapter02/Ch02_Code/GUI_embed_frames.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | from tkinter import scrolledtext 11 | 12 | # Create instance 13 | win = tk.Tk() 14 | 15 | # Add a title 16 | win.title("Python GUI") 17 | 18 | # We are creating a container frame to hold all other widgets 19 | mighty = ttk.LabelFrame(win, text=' Mighty Python ') 20 | mighty.grid(column=0, row=0, padx=8, pady=4) 21 | 22 | # Modify adding a Label using mighty as the parent instead of win 23 | a_label = ttk.Label(mighty, text="Enter a name:") 24 | a_label.grid(column=0, row=0) 25 | 26 | # Modified Button Click Function 27 | def click_me(): 28 | action.configure(text='Hello ' + name.get() + ' ' + 29 | number_chosen.get()) 30 | 31 | # Adding a Textbox Entry widget 32 | name = tk.StringVar() 33 | name_entered = ttk.Entry(mighty, width=12, textvariable=name) 34 | name_entered.grid(column=0, row=1) 35 | 36 | # Adding a Button 37 | action = ttk.Button(mighty, text="Click Me!", command=click_me) 38 | action.grid(column=2, row=1) # <= change column to 2 39 | 40 | # Creating three checkbuttons 41 | ttk.Label(mighty, text="Choose a number:").grid(column=1, row=0) 42 | number = tk.StringVar() 43 | number_chosen = ttk.Combobox(mighty, width=12, textvariable=number, state='readonly') 44 | number_chosen['values'] = (1, 2, 4, 42, 100) 45 | number_chosen.grid(column=1, row=1) 46 | number_chosen.current(0) 47 | 48 | chVarDis = tk.IntVar() 49 | check1 = tk.Checkbutton(mighty, text="Disabled", variable=chVarDis, state='disabled') 50 | check1.select() 51 | check1.grid(column=0, row=4, sticky=tk.W) 52 | 53 | chVarUn = tk.IntVar() 54 | check2 = tk.Checkbutton(mighty, text="UnChecked", variable=chVarUn) 55 | check2.deselect() 56 | check2.grid(column=1, row=4, sticky=tk.W) 57 | 58 | chVarEn = tk.IntVar() 59 | check3 = tk.Checkbutton(mighty, text="Enabled", variable=chVarEn) 60 | check3.deselect() 61 | check3.grid(column=2, row=4, sticky=tk.W) 62 | 63 | # GUI Callback function 64 | def checkCallback(*ignoredArgs): 65 | # only enable one checkbutton 66 | if chVarUn.get(): check3.configure(state='disabled') 67 | else: check3.configure(state='normal') 68 | if chVarEn.get(): check2.configure(state='disabled') 69 | else: check2.configure(state='normal') 70 | 71 | # trace the state of the two checkbuttons 72 | chVarUn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 73 | chVarEn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 74 | 75 | 76 | # Using a scrolled Text control 77 | scrol_w = 30 78 | scrol_h = 3 79 | scr = scrolledtext.ScrolledText(mighty, width=scrol_w, height=scrol_h, wrap=tk.WORD) 80 | #### scr.grid(column=0, row=5, sticky='WE', columnspan=3) 81 | scr.grid(column=0, row=5, columnspan=3) # sticky property removed 82 | 83 | 84 | # First, we change our Radiobutton global variables into a list 85 | colors = ["Blue", "Gold", "Red"] 86 | 87 | # We have also changed the callback function to be zero-based, using the list 88 | # instead of module-level global variables 89 | # Radiobutton Callback 90 | def radCall(): 91 | radSel=radVar.get() 92 | if radSel == 0: win.configure(background=colors[0]) # zero-based 93 | elif radSel == 1: win.configure(background=colors[1]) # using list 94 | elif radSel == 2: win.configure(background=colors[2]) 95 | 96 | # create three Radiobuttons using one variable 97 | radVar = tk.IntVar() 98 | 99 | # Next we are selecting a non-existing index value for radVar 100 | radVar.set(99) 101 | 102 | # Now we are creating all three Radiobutton widgets within one loop 103 | for col in range(3): 104 | curRad = tk.Radiobutton(mighty, text=colors[col], variable=radVar, 105 | value=col, command=radCall) 106 | curRad.grid(column=col, row=6, sticky=tk.W) # row=6 107 | 108 | # Create a container to hold labels 109 | buttons_frame = ttk.LabelFrame(mighty, text=' Labels in a Frame ') 110 | buttons_frame.grid(column=1, row=7) # now col 1 111 | 112 | # Place labels into the container element 113 | ttk.Label(buttons_frame, text="Label1").grid(column=0, row=0, sticky=tk.W) 114 | ttk.Label(buttons_frame, text="Label2").grid(column=1, row=0, sticky=tk.W) 115 | ttk.Label(buttons_frame, text="Label3").grid(column=2, row=0, sticky=tk.W) 116 | 117 | name_entered.focus() # Place cursor into name Entry 118 | #====================== 119 | # Start GUI 120 | #====================== 121 | win.mainloop() -------------------------------------------------------------------------------- /Chapter02/Ch02_Code/GUI_embed_frames_align.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | from tkinter import scrolledtext 11 | 12 | # Create instance 13 | win = tk.Tk() 14 | 15 | # Add a title 16 | win.title("Python GUI") 17 | 18 | # We are creating a container frame to hold all other widgets 19 | mighty = ttk.LabelFrame(win, text=' Mighty Python ') 20 | mighty.grid(column=0, row=0, padx=8, pady=4) 21 | 22 | # Modify adding a Label using mighty as the parent instead of win 23 | a_label = ttk.Label(mighty, text="Enter a name:") 24 | a_label.grid(column=0, row=0) 25 | 26 | # Modified Button Click Function 27 | def click_me(): 28 | action.configure(text='Hello ' + name.get() + ' ' + 29 | number_chosen.get()) 30 | 31 | # Adding a Textbox Entry widget 32 | name = tk.StringVar() 33 | name_entered = ttk.Entry(mighty, width=12, textvariable=name) 34 | name_entered.grid(column=0, row=1) 35 | 36 | # Adding a Button 37 | action = ttk.Button(mighty, text="Click Me!", command=click_me) 38 | action.grid(column=2, row=1) # <= change column to 2 39 | 40 | # Creating three checkbuttons 41 | ttk.Label(mighty, text="Choose a number:").grid(column=1, row=0) 42 | number = tk.StringVar() 43 | number_chosen = ttk.Combobox(mighty, width=12, textvariable=number, state='readonly') 44 | number_chosen['values'] = (1, 2, 4, 42, 100) 45 | number_chosen.grid(column=1, row=1) 46 | number_chosen.current(0) 47 | 48 | chVarDis = tk.IntVar() 49 | check1 = tk.Checkbutton(mighty, text="Disabled", variable=chVarDis, state='disabled') 50 | check1.select() 51 | check1.grid(column=0, row=4, sticky=tk.W) 52 | 53 | chVarUn = tk.IntVar() 54 | check2 = tk.Checkbutton(mighty, text="UnChecked", variable=chVarUn) 55 | check2.deselect() 56 | check2.grid(column=1, row=4, sticky=tk.W) 57 | 58 | chVarEn = tk.IntVar() 59 | check3 = tk.Checkbutton(mighty, text="Enabled", variable=chVarEn) 60 | check3.deselect() 61 | check3.grid(column=2, row=4, sticky=tk.W) 62 | 63 | # GUI Callback function 64 | def checkCallback(*ignoredArgs): 65 | # only enable one checkbutton 66 | if chVarUn.get(): check3.configure(state='disabled') 67 | else: check3.configure(state='normal') 68 | if chVarEn.get(): check2.configure(state='disabled') 69 | else: check2.configure(state='normal') 70 | 71 | # trace the state of the two checkbuttons 72 | chVarUn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 73 | chVarEn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 74 | 75 | 76 | # Using a scrolled Text control 77 | scrol_w = 30 78 | scrol_h = 3 79 | scr = scrolledtext.ScrolledText(mighty, width=scrol_w, height=scrol_h, wrap=tk.WORD) 80 | #### scr.grid(column=0, row=5, sticky='WE', columnspan=3) 81 | scr.grid(column=0, row=5, columnspan=3) # sticky property removed 82 | 83 | 84 | # First, we change our Radiobutton global variables into a list 85 | colors = ["Blue", "Gold", "Red"] 86 | 87 | # We have also changed the callback function to be zero-based, using the list 88 | # instead of module-level global variables 89 | # Radiobutton Callback 90 | def radCall(): 91 | radSel=radVar.get() 92 | if radSel == 0: win.configure(background=colors[0]) # zero-based 93 | elif radSel == 1: win.configure(background=colors[1]) # using list 94 | elif radSel == 2: win.configure(background=colors[2]) 95 | 96 | # create three Radiobuttons using one variable 97 | radVar = tk.IntVar() 98 | 99 | # Next we are selecting a non-existing index value for radVar 100 | radVar.set(99) 101 | 102 | # Now we are creating all three Radiobutton widgets within one loop 103 | for col in range(3): 104 | curRad = tk.Radiobutton(mighty, text=colors[col], variable=radVar, 105 | value=col, command=radCall) 106 | curRad.grid(column=col, row=6, sticky=tk.W) # row=6 107 | 108 | # Create a container to hold labels 109 | buttons_frame = ttk.LabelFrame(mighty, text=' Labels in a Frame ') 110 | buttons_frame.grid(column=0, row=7) 111 | 112 | # Place labels into the container element 113 | ttk.Label(buttons_frame, text="Label1").grid(column=0, row=0, sticky=tk.W) 114 | ttk.Label(buttons_frame, text="Label2").grid(column=1, row=0, sticky=tk.W) 115 | ttk.Label(buttons_frame, text="Label3").grid(column=2, row=0, sticky=tk.W) 116 | 117 | name_entered.focus() # Place cursor into name Entry 118 | #====================== 119 | # Start GUI 120 | #====================== 121 | win.mainloop() -------------------------------------------------------------------------------- /Chapter02/Ch02_Code/GUI_embed_frames_align_entry_west.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | from tkinter import scrolledtext 11 | 12 | # Create instance 13 | win = tk.Tk() 14 | 15 | # Add a title 16 | win.title("Python GUI") 17 | 18 | # We are creating a container frame to hold all other widgets 19 | mighty = ttk.LabelFrame(win, text=' Mighty Python ') 20 | mighty.grid(column=0, row=0, padx=8, pady=4) 21 | 22 | # Modify adding a Label using mighty as the parent instead of win 23 | a_label = ttk.Label(mighty, text="Enter a name:") 24 | a_label.grid(column=0, row=0, sticky='W') 25 | 26 | # Modified Button Click Function 27 | def click_me(): 28 | action.configure(text='Hello ' + name.get() + ' ' + 29 | number_chosen.get()) 30 | 31 | # Adding a Textbox Entry widget 32 | name = tk.StringVar() 33 | name_entered = ttk.Entry(mighty, width=12, textvariable=name) 34 | name_entered.grid(column=0, row=1, sticky=tk.W) # align left/West 35 | 36 | # Adding a Button 37 | action = ttk.Button(mighty, text="Click Me!", command=click_me) 38 | action.grid(column=2, row=1) 39 | 40 | # Creating three checkbuttons 41 | ttk.Label(mighty, text="Choose a number:").grid(column=1, row=0) 42 | number = tk.StringVar() 43 | number_chosen = ttk.Combobox(mighty, width=12, textvariable=number, state='readonly') 44 | number_chosen['values'] = (1, 2, 4, 42, 100) 45 | number_chosen.grid(column=1, row=1) 46 | number_chosen.current(0) 47 | 48 | chVarDis = tk.IntVar() 49 | check1 = tk.Checkbutton(mighty, text="Disabled", variable=chVarDis, state='disabled') 50 | check1.select() 51 | check1.grid(column=0, row=4, sticky=tk.W) 52 | 53 | chVarUn = tk.IntVar() 54 | check2 = tk.Checkbutton(mighty, text="UnChecked", variable=chVarUn) 55 | check2.deselect() 56 | check2.grid(column=1, row=4, sticky=tk.W) 57 | 58 | chVarEn = tk.IntVar() 59 | check3 = tk.Checkbutton(mighty, text="Enabled", variable=chVarEn) 60 | check3.deselect() 61 | check3.grid(column=2, row=4, sticky=tk.W) 62 | 63 | # GUI Callback function 64 | def checkCallback(*ignoredArgs): 65 | # only enable one checkbutton 66 | if chVarUn.get(): check3.configure(state='disabled') 67 | else: check3.configure(state='normal') 68 | if chVarEn.get(): check2.configure(state='disabled') 69 | else: check2.configure(state='normal') 70 | 71 | # trace the state of the two checkbuttons 72 | chVarUn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 73 | chVarEn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 74 | 75 | 76 | # Using a scrolled Text control 77 | scrol_w = 30 78 | scrol_h = 3 79 | scr = scrolledtext.ScrolledText(mighty, width=scrol_w, height=scrol_h, wrap=tk.WORD) 80 | #### scr.grid(column=0, row=5, sticky='WE', columnspan=3) 81 | scr.grid(column=0, row=5, columnspan=3) # sticky property removed 82 | 83 | 84 | # First, we change our Radiobutton global variables into a list 85 | colors = ["Blue", "Gold", "Red"] 86 | 87 | # We have also changed the callback function to be zero-based, using the list 88 | # instead of module-level global variables 89 | # Radiobutton Callback 90 | def radCall(): 91 | radSel=radVar.get() 92 | if radSel == 0: win.configure(background=colors[0]) # zero-based 93 | elif radSel == 1: win.configure(background=colors[1]) # using list 94 | elif radSel == 2: win.configure(background=colors[2]) 95 | 96 | # create three Radiobuttons using one variable 97 | radVar = tk.IntVar() 98 | 99 | # Next we are selecting a non-existing index value for radVar 100 | radVar.set(99) 101 | 102 | # Now we are creating all three Radiobutton widgets within one loop 103 | for col in range(3): 104 | curRad = tk.Radiobutton(mighty, text=colors[col], variable=radVar, 105 | value=col, command=radCall) 106 | curRad.grid(column=col, row=6, sticky=tk.W) # row=6 107 | 108 | # Create a container to hold labels 109 | buttons_frame = ttk.LabelFrame(mighty, text=' Labels in a Frame ') 110 | buttons_frame.grid(column=0, row=7) 111 | 112 | # Place labels into the container element 113 | ttk.Label(buttons_frame, text="Label1").grid(column=0, row=0, sticky=tk.W) 114 | ttk.Label(buttons_frame, text="Label2").grid(column=1, row=0, sticky=tk.W) 115 | ttk.Label(buttons_frame, text="Label3").grid(column=2, row=0, sticky=tk.W) 116 | 117 | name_entered.focus() # Place cursor into name Entry 118 | #====================== 119 | # Start GUI 120 | #====================== 121 | win.mainloop() -------------------------------------------------------------------------------- /Chapter02/Ch02_Code/GUI_embed_frames_align_west.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | from tkinter import scrolledtext 11 | 12 | # Create instance 13 | win = tk.Tk() 14 | 15 | # Add a title 16 | win.title("Python GUI") 17 | 18 | # We are creating a container frame to hold all other widgets 19 | mighty = ttk.LabelFrame(win, text=' Mighty Python ') 20 | mighty.grid(column=0, row=0, padx=8, pady=4) 21 | 22 | # Modify adding a Label using mighty as the parent instead of win 23 | a_label = ttk.Label(mighty, text="Enter a name:") 24 | a_label.grid(column=0, row=0, sticky='W') 25 | 26 | # Modified Button Click Function 27 | def click_me(): 28 | action.configure(text='Hello ' + name.get() + ' ' + 29 | number_chosen.get()) 30 | 31 | # Adding a Textbox Entry widget 32 | name = tk.StringVar() 33 | name_entered = ttk.Entry(mighty, width=12, textvariable=name) 34 | name_entered.grid(column=0, row=1) 35 | 36 | # Adding a Button 37 | action = ttk.Button(mighty, text="Click Me!", command=click_me) 38 | action.grid(column=2, row=1) # <= change column to 2 39 | 40 | # Creating three checkbuttons 41 | ttk.Label(mighty, text="Choose a number:").grid(column=1, row=0) 42 | number = tk.StringVar() 43 | number_chosen = ttk.Combobox(mighty, width=12, textvariable=number, state='readonly') 44 | number_chosen['values'] = (1, 2, 4, 42, 100) 45 | number_chosen.grid(column=1, row=1) 46 | number_chosen.current(0) 47 | 48 | chVarDis = tk.IntVar() 49 | check1 = tk.Checkbutton(mighty, text="Disabled", variable=chVarDis, state='disabled') 50 | check1.select() 51 | check1.grid(column=0, row=4, sticky=tk.W) 52 | 53 | chVarUn = tk.IntVar() 54 | check2 = tk.Checkbutton(mighty, text="UnChecked", variable=chVarUn) 55 | check2.deselect() 56 | check2.grid(column=1, row=4, sticky=tk.W) 57 | 58 | chVarEn = tk.IntVar() 59 | check3 = tk.Checkbutton(mighty, text="Enabled", variable=chVarEn) 60 | check3.deselect() 61 | check3.grid(column=2, row=4, sticky=tk.W) 62 | 63 | # GUI Callback function 64 | def checkCallback(*ignoredArgs): 65 | # only enable one checkbutton 66 | if chVarUn.get(): check3.configure(state='disabled') 67 | else: check3.configure(state='normal') 68 | if chVarEn.get(): check2.configure(state='disabled') 69 | else: check2.configure(state='normal') 70 | 71 | # trace the state of the two checkbuttons 72 | chVarUn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 73 | chVarEn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 74 | 75 | 76 | # Using a scrolled Text control 77 | scrol_w = 30 78 | scrol_h = 3 79 | scr = scrolledtext.ScrolledText(mighty, width=scrol_w, height=scrol_h, wrap=tk.WORD) 80 | #### scr.grid(column=0, row=5, sticky='WE', columnspan=3) 81 | scr.grid(column=0, row=5, columnspan=3) # sticky property removed 82 | 83 | 84 | # First, we change our Radiobutton global variables into a list 85 | colors = ["Blue", "Gold", "Red"] 86 | 87 | # We have also changed the callback function to be zero-based, using the list 88 | # instead of module-level global variables 89 | # Radiobutton Callback 90 | def radCall(): 91 | radSel=radVar.get() 92 | if radSel == 0: win.configure(background=colors[0]) # zero-based 93 | elif radSel == 1: win.configure(background=colors[1]) # using list 94 | elif radSel == 2: win.configure(background=colors[2]) 95 | 96 | # create three Radiobuttons using one variable 97 | radVar = tk.IntVar() 98 | 99 | # Next we are selecting a non-existing index value for radVar 100 | radVar.set(99) 101 | 102 | # Now we are creating all three Radiobutton widgets within one loop 103 | for col in range(3): 104 | curRad = tk.Radiobutton(mighty, text=colors[col], variable=radVar, 105 | value=col, command=radCall) 106 | curRad.grid(column=col, row=6, sticky=tk.W) # row=6 107 | 108 | # Create a container to hold labels 109 | buttons_frame = ttk.LabelFrame(mighty, text=' Labels in a Frame ') 110 | buttons_frame.grid(column=0, row=7) 111 | 112 | # Place labels into the container element 113 | ttk.Label(buttons_frame, text="Label1").grid(column=0, row=0, sticky=tk.W) 114 | ttk.Label(buttons_frame, text="Label2").grid(column=1, row=0, sticky=tk.W) 115 | ttk.Label(buttons_frame, text="Label3").grid(column=2, row=0, sticky=tk.W) 116 | 117 | name_entered.focus() # Place cursor into name Entry 118 | #====================== 119 | # Start GUI 120 | #====================== 121 | win.mainloop() -------------------------------------------------------------------------------- /Chapter02/Ch02_Code/GUI_long_label.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | from tkinter import scrolledtext 11 | 12 | # Create instance 13 | win = tk.Tk() 14 | 15 | # Add a title 16 | win.title("Python GUI") 17 | 18 | # Modify adding a Label 19 | a_label = ttk.Label(win, text="A Label") 20 | a_label.grid(column=0, row=0) 21 | 22 | # Modified Button Click Function 23 | def click_me(): 24 | action.configure(text='Hello ' + name.get() + ' ' + 25 | number_chosen.get()) 26 | 27 | # Changing our Label 28 | ttk.Label(win, text="Enter a name:").grid(column=0, row=0) 29 | 30 | # Adding a Textbox Entry widget 31 | name = tk.StringVar() 32 | name_entered = ttk.Entry(win, width=12, textvariable=name) 33 | name_entered.grid(column=0, row=1) 34 | 35 | # Adding a Button 36 | action = ttk.Button(win, text="Click Me!", command=click_me) 37 | action.grid(column=2, row=1) # <= change column to 2 38 | 39 | # Creating three checkbuttons 40 | ttk.Label(win, text="Choose a number:").grid(column=1, row=0) 41 | number = tk.StringVar() 42 | number_chosen = ttk.Combobox(win, width=12, textvariable=number, state='readonly') 43 | number_chosen['values'] = (1, 2, 4, 42, 100) 44 | number_chosen.grid(column=1, row=1) 45 | number_chosen.current(0) 46 | 47 | chVarDis = tk.IntVar() 48 | check1 = tk.Checkbutton(win, text="Disabled", variable=chVarDis, state='disabled') 49 | check1.select() 50 | check1.grid(column=0, row=4, sticky=tk.W) 51 | 52 | chVarUn = tk.IntVar() 53 | check2 = tk.Checkbutton(win, text="UnChecked", variable=chVarUn) 54 | check2.deselect() 55 | check2.grid(column=1, row=4, sticky=tk.W) 56 | 57 | chVarEn = tk.IntVar() 58 | check3 = tk.Checkbutton(win, text="Enabled", variable=chVarEn) 59 | check3.deselect() 60 | check3.grid(column=2, row=4, sticky=tk.W) 61 | 62 | # GUI Callback function 63 | def checkCallback(*ignoredArgs): 64 | # only enable one checkbutton 65 | if chVarUn.get(): check3.configure(state='disabled') 66 | else: check3.configure(state='normal') 67 | if chVarEn.get(): check2.configure(state='disabled') 68 | else: check2.configure(state='normal') 69 | 70 | # trace the state of the two checkbuttons 71 | chVarUn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 72 | chVarEn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 73 | 74 | 75 | # Using a scrolled Text control 76 | scrol_w = 30 77 | scrol_h = 3 78 | scr = scrolledtext.ScrolledText(win, width=scrol_w, height=scrol_h, wrap=tk.WORD) 79 | scr.grid(column=0, row=5, sticky='WE', columnspan=3) # row=5 80 | 81 | # First, we change our Radiobutton global variables into a list 82 | colors = ["Blue", "Gold", "Red"] 83 | 84 | # We have also changed the callback function to be zero-based, using the list 85 | # instead of module-level global variables 86 | # Radiobutton Callback 87 | def radCall(): 88 | radSel=radVar.get() 89 | if radSel == 0: win.configure(background=colors[0]) # zero-based 90 | elif radSel == 1: win.configure(background=colors[1]) # using list 91 | elif radSel == 2: win.configure(background=colors[2]) 92 | 93 | # create three Radiobuttons using one variable 94 | radVar = tk.IntVar() 95 | 96 | # Next we are selecting a non-existing index value for radVar 97 | radVar.set(99) 98 | 99 | # Now we are creating all three Radiobutton widgets within one loop 100 | for col in range(3): 101 | curRad = tk.Radiobutton(win, text=colors[col], variable=radVar, 102 | value=col, command=radCall) 103 | curRad.grid(column=col, row=6, sticky=tk.W) # row=6 104 | 105 | # Create a container to hold labels 106 | buttons_frame = ttk.LabelFrame(win, text=' Labels in a Frame ') 107 | buttons_frame.grid(column=0, row=7, padx=20, pady=40) # padx, pady 108 | 109 | 110 | 111 | 112 | # Place labels into the container element - vertically with long label 113 | ttk.Label(buttons_frame, text="Label1 -- sooooo much loooonger...").grid(column=0, row=0) 114 | ttk.Label(buttons_frame, text="Label2").grid(column=0, row=1) 115 | ttk.Label(buttons_frame, text="Label3").grid(column=0, row=2) 116 | 117 | for child in buttons_frame.winfo_children(): 118 | child.grid_configure(padx=8, pady=4) 119 | 120 | name_entered.focus() # Place cursor into name Entry 121 | #====================== 122 | # Start GUI 123 | #====================== 124 | win.mainloop() 125 | -------------------------------------------------------------------------------- /Chapter02/Ch02_Code/GUI_menubar_exit.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | from tkinter import scrolledtext 11 | from tkinter import Menu 12 | 13 | # Create instance 14 | win = tk.Tk() 15 | 16 | # Add a title 17 | win.title("Python GUI") 18 | 19 | # We are creating a container frame to hold all other widgets 20 | mighty = ttk.LabelFrame(win, text=' Mighty Python ') 21 | mighty.grid(column=0, row=0, padx=8, pady=4) 22 | 23 | # Modify adding a Label using mighty as the parent instead of win 24 | a_label = ttk.Label(mighty, text="Enter a name:") 25 | a_label.grid(column=0, row=0, sticky='W') 26 | 27 | # Modified Button Click Function 28 | def click_me(): 29 | action.configure(text='Hello ' + name.get() + ' ' + 30 | number_chosen.get()) 31 | 32 | # Adding a Textbox Entry widget 33 | name = tk.StringVar() 34 | name_entered = ttk.Entry(mighty, width=12, textvariable=name) 35 | name_entered.grid(column=0, row=1, sticky='W') # align left/West 36 | 37 | # Adding a Button 38 | action = ttk.Button(mighty, text="Click Me!", command=click_me) 39 | action.grid(column=2, row=1) 40 | 41 | # Creating three checkbuttons 42 | ttk.Label(mighty, text="Choose a number:").grid(column=1, row=0) 43 | number = tk.StringVar() 44 | number_chosen = ttk.Combobox(mighty, width=12, textvariable=number, state='readonly') 45 | number_chosen['values'] = (1, 2, 4, 42, 100) 46 | number_chosen.grid(column=1, row=1) 47 | number_chosen.current(0) 48 | 49 | chVarDis = tk.IntVar() 50 | check1 = tk.Checkbutton(mighty, text="Disabled", variable=chVarDis, state='disabled') 51 | check1.select() 52 | check1.grid(column=0, row=4, sticky=tk.W) 53 | 54 | chVarUn = tk.IntVar() 55 | check2 = tk.Checkbutton(mighty, text="UnChecked", variable=chVarUn) 56 | check2.deselect() 57 | check2.grid(column=1, row=4, sticky=tk.W) 58 | 59 | chVarEn = tk.IntVar() 60 | check3 = tk.Checkbutton(mighty, text="Enabled", variable=chVarEn) 61 | check3.deselect() 62 | check3.grid(column=2, row=4, sticky=tk.W) 63 | 64 | # GUI Callback function 65 | def checkCallback(*ignoredArgs): 66 | # only enable one checkbutton 67 | if chVarUn.get(): check3.configure(state='disabled') 68 | else: check3.configure(state='normal') 69 | if chVarEn.get(): check2.configure(state='disabled') 70 | else: check2.configure(state='normal') 71 | 72 | # trace the state of the two checkbuttons 73 | chVarUn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 74 | chVarEn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 75 | 76 | 77 | # Using a scrolled Text control 78 | scrol_w = 30 79 | scrol_h = 3 80 | scr = scrolledtext.ScrolledText(mighty, width=scrol_w, height=scrol_h, wrap=tk.WORD) 81 | #### scr.grid(column=0, row=5, sticky='WE', columnspan=3) 82 | scr.grid(column=0, row=5, columnspan=3) # sticky property removed 83 | 84 | # First, we change our Radiobutton global variables into a list 85 | colors = ["Blue", "Gold", "Red"] 86 | 87 | # We have also changed the callback function to be zero-based, using the list 88 | # instead of module-level global variables 89 | # Radiobutton Callback 90 | def radCall(): 91 | radSel=radVar.get() 92 | if radSel == 0: win.configure(background=colors[0]) # zero-based 93 | elif radSel == 1: win.configure(background=colors[1]) # using list 94 | elif radSel == 2: win.configure(background=colors[2]) 95 | 96 | # create three Radiobuttons using one variable 97 | radVar = tk.IntVar() 98 | 99 | # Next we are selecting a non-existing index value for radVar 100 | radVar.set(99) 101 | 102 | # Now we are creating all three Radiobutton widgets within one loop 103 | for col in range(3): 104 | curRad = tk.Radiobutton(mighty, text=colors[col], variable=radVar, 105 | value=col, command=radCall) 106 | curRad.grid(column=col, row=6, sticky=tk.W) # row=6 107 | 108 | # Create a container to hold labels 109 | buttons_frame = ttk.LabelFrame(mighty, text=' Labels in a Frame ') 110 | buttons_frame.grid(column=0, row=7) 111 | 112 | # Place labels into the container element 113 | ttk.Label(buttons_frame, text="Label1").grid(column=0, row=0, sticky=tk.W) 114 | ttk.Label(buttons_frame, text="Label2").grid(column=1, row=0, sticky=tk.W) 115 | ttk.Label(buttons_frame, text="Label3").grid(column=2, row=0, sticky=tk.W) 116 | 117 | # Creating a Menu Bar 118 | menu_bar = Menu(win) 119 | win.config(menu=menu_bar) 120 | 121 | # Add menu items 122 | file_menu = Menu(menu_bar) 123 | file_menu.add_command(label="New") 124 | file_menu.add_command(label="Exit") 125 | menu_bar.add_cascade(label="File", menu=file_menu) 126 | 127 | name_entered.focus() # Place cursor into name Entry 128 | #====================== 129 | # Start GUI 130 | #====================== 131 | win.mainloop() -------------------------------------------------------------------------------- /Chapter02/Ch02_Code/GUI_menubar_separator.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | from tkinter import scrolledtext 11 | from tkinter import Menu 12 | 13 | # Create instance 14 | win = tk.Tk() 15 | 16 | # Add a title 17 | win.title("Python GUI") 18 | 19 | # We are creating a container frame to hold all other widgets 20 | mighty = ttk.LabelFrame(win, text=' Mighty Python ') 21 | mighty.grid(column=0, row=0, padx=8, pady=4) 22 | 23 | # Modify adding a Label using mighty as the parent instead of win 24 | a_label = ttk.Label(mighty, text="Enter a name:") 25 | a_label.grid(column=0, row=0, sticky='W') 26 | 27 | # Modified Button Click Function 28 | def click_me(): 29 | action.configure(text='Hello ' + name.get() + ' ' + 30 | number_chosen.get()) 31 | 32 | # Adding a Textbox Entry widget 33 | name = tk.StringVar() 34 | name_entered = ttk.Entry(mighty, width=12, textvariable=name) 35 | name_entered.grid(column=0, row=1, sticky='W') # align left/West 36 | 37 | # Adding a Button 38 | action = ttk.Button(mighty, text="Click Me!", command=click_me) 39 | action.grid(column=2, row=1) 40 | 41 | # Creating three checkbuttons 42 | ttk.Label(mighty, text="Choose a number:").grid(column=1, row=0) 43 | number = tk.StringVar() 44 | number_chosen = ttk.Combobox(mighty, width=12, textvariable=number, state='readonly') 45 | number_chosen['values'] = (1, 2, 4, 42, 100) 46 | number_chosen.grid(column=1, row=1) 47 | number_chosen.current(0) 48 | 49 | chVarDis = tk.IntVar() 50 | check1 = tk.Checkbutton(mighty, text="Disabled", variable=chVarDis, state='disabled') 51 | check1.select() 52 | check1.grid(column=0, row=4, sticky=tk.W) 53 | 54 | chVarUn = tk.IntVar() 55 | check2 = tk.Checkbutton(mighty, text="UnChecked", variable=chVarUn) 56 | check2.deselect() 57 | check2.grid(column=1, row=4, sticky=tk.W) 58 | 59 | chVarEn = tk.IntVar() 60 | check3 = tk.Checkbutton(mighty, text="Enabled", variable=chVarEn) 61 | check3.deselect() 62 | check3.grid(column=2, row=4, sticky=tk.W) 63 | 64 | # GUI Callback function 65 | def checkCallback(*ignoredArgs): 66 | # only enable one checkbutton 67 | if chVarUn.get(): check3.configure(state='disabled') 68 | else: check3.configure(state='normal') 69 | if chVarEn.get(): check2.configure(state='disabled') 70 | else: check2.configure(state='normal') 71 | 72 | # trace the state of the two checkbuttons 73 | chVarUn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 74 | chVarEn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 75 | 76 | 77 | # Using a scrolled Text control 78 | scrol_w = 30 79 | scrol_h = 3 80 | scr = scrolledtext.ScrolledText(mighty, width=scrol_w, height=scrol_h, wrap=tk.WORD) 81 | #### scr.grid(column=0, row=5, sticky='WE', columnspan=3) 82 | scr.grid(column=0, row=5, columnspan=3) # sticky property removed 83 | 84 | 85 | # First, we change our Radiobutton global variables into a list 86 | colors = ["Blue", "Gold", "Red"] 87 | 88 | # We have also changed the callback function to be zero-based, using the list 89 | # instead of module-level global variables 90 | # Radiobutton Callback 91 | def radCall(): 92 | radSel=radVar.get() 93 | if radSel == 0: win.configure(background=colors[0]) # zero-based 94 | elif radSel == 1: win.configure(background=colors[1]) # using list 95 | elif radSel == 2: win.configure(background=colors[2]) 96 | 97 | # create three Radiobuttons using one variable 98 | radVar = tk.IntVar() 99 | 100 | # Next we are selecting a non-existing index value for radVar 101 | radVar.set(99) 102 | 103 | # Now we are creating all three Radiobutton widgets within one loop 104 | for col in range(3): 105 | curRad = tk.Radiobutton(mighty, text=colors[col], variable=radVar, 106 | value=col, command=radCall) 107 | curRad.grid(column=col, row=6, sticky=tk.W) # row=6 108 | 109 | # Create a container to hold labels 110 | buttons_frame = ttk.LabelFrame(mighty, text=' Labels in a Frame ') 111 | buttons_frame.grid(column=0, row=7) 112 | 113 | # Place labels into the container element 114 | ttk.Label(buttons_frame, text="Label1").grid(column=0, row=0, sticky=tk.W) 115 | ttk.Label(buttons_frame, text="Label2").grid(column=1, row=0, sticky=tk.W) 116 | ttk.Label(buttons_frame, text="Label3").grid(column=2, row=0, sticky=tk.W) 117 | 118 | 119 | # Creating a Menu Bar 120 | menu_bar = Menu(win) 121 | win.config(menu=menu_bar) 122 | 123 | # Add menu items 124 | file_menu = Menu(menu_bar) 125 | file_menu.add_command(label="New") 126 | file_menu.add_separator() 127 | file_menu.add_command(label="Exit") 128 | menu_bar.add_cascade(label="File", menu=file_menu) 129 | 130 | 131 | name_entered.focus() # Place cursor into name Entry 132 | #====================== 133 | # Start GUI 134 | #====================== 135 | win.mainloop() -------------------------------------------------------------------------------- /Chapter02/Ch02_Code/GUI_menubar_tearoff.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | from tkinter import scrolledtext 11 | from tkinter import Menu 12 | 13 | # Create instance 14 | win = tk.Tk() 15 | 16 | # Add a title 17 | win.title("Python GUI") 18 | 19 | # We are creating a container frame to hold all other widgets 20 | mighty = ttk.LabelFrame(win, text=' Mighty Python ') 21 | mighty.grid(column=0, row=0, padx=8, pady=4) 22 | 23 | # Modify adding a Label using mighty as the parent instead of win 24 | a_label = ttk.Label(mighty, text="Enter a name:") 25 | a_label.grid(column=0, row=0, sticky='W') 26 | 27 | # Modified Button Click Function 28 | def click_me(): 29 | action.configure(text='Hello ' + name.get() + ' ' + 30 | number_chosen.get()) 31 | 32 | # Adding a Textbox Entry widget 33 | name = tk.StringVar() 34 | name_entered = ttk.Entry(mighty, width=12, textvariable=name) 35 | name_entered.grid(column=0, row=1, sticky='W') # align left/West 36 | 37 | # Adding a Button 38 | action = ttk.Button(mighty, text="Click Me!", command=click_me) 39 | action.grid(column=2, row=1) 40 | 41 | # Creating three checkbuttons 42 | ttk.Label(mighty, text="Choose a number:").grid(column=1, row=0) 43 | number = tk.StringVar() 44 | number_chosen = ttk.Combobox(mighty, width=12, textvariable=number, state='readonly') 45 | number_chosen['values'] = (1, 2, 4, 42, 100) 46 | number_chosen.grid(column=1, row=1) 47 | number_chosen.current(0) 48 | 49 | chVarDis = tk.IntVar() 50 | check1 = tk.Checkbutton(mighty, text="Disabled", variable=chVarDis, state='disabled') 51 | check1.select() 52 | check1.grid(column=0, row=4, sticky=tk.W) 53 | 54 | chVarUn = tk.IntVar() 55 | check2 = tk.Checkbutton(mighty, text="UnChecked", variable=chVarUn) 56 | check2.deselect() 57 | check2.grid(column=1, row=4, sticky=tk.W) 58 | 59 | chVarEn = tk.IntVar() 60 | check3 = tk.Checkbutton(mighty, text="Enabled", variable=chVarEn) 61 | check3.deselect() 62 | check3.grid(column=2, row=4, sticky=tk.W) 63 | 64 | # GUI Callback function 65 | def checkCallback(*ignoredArgs): 66 | # only enable one checkbutton 67 | if chVarUn.get(): check3.configure(state='disabled') 68 | else: check3.configure(state='normal') 69 | if chVarEn.get(): check2.configure(state='disabled') 70 | else: check2.configure(state='normal') 71 | 72 | # trace the state of the two checkbuttons 73 | chVarUn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 74 | chVarEn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 75 | 76 | 77 | # Using a scrolled Text control 78 | scrol_w = 30 79 | scrol_h = 3 80 | scr = scrolledtext.ScrolledText(mighty, width=scrol_w, height=scrol_h, wrap=tk.WORD) 81 | #### scr.grid(column=0, row=5, sticky='WE', columnspan=3) 82 | scr.grid(column=0, row=5, columnspan=3) # sticky property removed 83 | 84 | 85 | # First, we change our Radiobutton global variables into a list 86 | colors = ["Blue", "Gold", "Red"] 87 | 88 | # We have also changed the callback function to be zero-based, using the list 89 | # instead of module-level global variables 90 | # Radiobutton Callback 91 | def radCall(): 92 | radSel=radVar.get() 93 | if radSel == 0: win.configure(background=colors[0]) # zero-based 94 | elif radSel == 1: win.configure(background=colors[1]) # using list 95 | elif radSel == 2: win.configure(background=colors[2]) 96 | 97 | # create three Radiobuttons using one variable 98 | radVar = tk.IntVar() 99 | 100 | # Next we are selecting a non-existing index value for radVar 101 | radVar.set(99) 102 | 103 | # Now we are creating all three Radiobutton widgets within one loop 104 | for col in range(3): 105 | curRad = tk.Radiobutton(mighty, text=colors[col], variable=radVar, 106 | value=col, command=radCall) 107 | curRad.grid(column=col, row=6, sticky=tk.W) # row=6 108 | 109 | # Create a container to hold labels 110 | buttons_frame = ttk.LabelFrame(mighty, text=' Labels in a Frame ') 111 | buttons_frame.grid(column=0, row=7) 112 | 113 | # Place labels into the container element 114 | ttk.Label(buttons_frame, text="Label1").grid(column=0, row=0, sticky=tk.W) 115 | ttk.Label(buttons_frame, text="Label2").grid(column=1, row=0, sticky=tk.W) 116 | ttk.Label(buttons_frame, text="Label3").grid(column=2, row=0, sticky=tk.W) 117 | 118 | 119 | # Creating a Menu Bar 120 | menu_bar = Menu(win) 121 | win.config(menu=menu_bar) 122 | 123 | # Add menu items 124 | file_menu = Menu(menu_bar, tearoff=0) 125 | file_menu.add_command(label="New") 126 | file_menu.add_separator() 127 | file_menu.add_command(label="Exit") 128 | menu_bar.add_cascade(label="File", menu=file_menu) 129 | 130 | 131 | name_entered.focus() # Place cursor into name Entry 132 | #====================== 133 | # Start GUI 134 | #====================== 135 | win.mainloop() -------------------------------------------------------------------------------- /Chapter02/Ch02_Code/GUI_remove_columnspan.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | from tkinter import scrolledtext 11 | 12 | # Create instance 13 | win = tk.Tk() 14 | 15 | # Add a title 16 | win.title("Python GUI") 17 | 18 | # Modify adding a Label 19 | a_label = ttk.Label(win, text="A Label") 20 | a_label.grid(column=0, row=0) 21 | 22 | # Modified Button Click Function 23 | def click_me(): 24 | action.configure(text='Hello ' + name.get() + ' ' + 25 | number_chosen.get()) 26 | 27 | # Changing our Label 28 | ttk.Label(win, text="Enter a name:").grid(column=0, row=0) 29 | 30 | # Adding a Textbox Entry widget 31 | name = tk.StringVar() 32 | name_entered = ttk.Entry(win, width=12, textvariable=name) 33 | name_entered.grid(column=0, row=1) 34 | 35 | # Adding a Button 36 | action = ttk.Button(win, text="Click Me!", command=click_me) 37 | action.grid(column=2, row=1) # <= change column to 2 38 | 39 | # Creating three checkbuttons 40 | ttk.Label(win, text="Choose a number:").grid(column=1, row=0) 41 | number = tk.StringVar() 42 | number_chosen = ttk.Combobox(win, width=12, textvariable=number, state='readonly') 43 | number_chosen['values'] = (1, 2, 4, 42, 100) 44 | number_chosen.grid(column=1, row=1) 45 | number_chosen.current(0) 46 | 47 | chVarDis = tk.IntVar() 48 | check1 = tk.Checkbutton(win, text="Disabled", variable=chVarDis, state='disabled') 49 | check1.select() 50 | check1.grid(column=0, row=4, sticky=tk.W) 51 | 52 | chVarUn = tk.IntVar() 53 | check2 = tk.Checkbutton(win, text="UnChecked", variable=chVarUn) 54 | check2.deselect() 55 | check2.grid(column=1, row=4, sticky=tk.W) 56 | 57 | chVarEn = tk.IntVar() 58 | check3 = tk.Checkbutton(win, text="Enabled", variable=chVarEn) 59 | check3.deselect() 60 | check3.grid(column=2, row=4, sticky=tk.W) 61 | 62 | # GUI Callback function 63 | def checkCallback(*ignoredArgs): 64 | # only enable one checkbutton 65 | if chVarUn.get(): check3.configure(state='disabled') 66 | else: check3.configure(state='normal') 67 | if chVarEn.get(): check2.configure(state='disabled') 68 | else: check2.configure(state='normal') 69 | 70 | # trace the state of the two checkbuttons 71 | chVarUn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 72 | chVarEn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 73 | 74 | 75 | # Using a scrolled Text control 76 | scrol_w = 30 77 | scrol_h = 3 78 | scr = scrolledtext.ScrolledText(win, width=scrol_w, height=scrol_h, wrap=tk.WORD) 79 | #### scr.grid(column=0, row=5, sticky='WE', columnspan=3) 80 | #### scr.grid(column=0, row=5, columnspan=3) # sticky property removed 81 | scr.grid(column=0, row=5) # columnspan removed 82 | 83 | # First, we change our Radiobutton global variables into a list 84 | colors = ["Blue", "Gold", "Red"] 85 | 86 | # We have also changed the callback function to be zero-based, using the list 87 | # instead of module-level global variables 88 | # Radiobutton Callback 89 | def radCall(): 90 | radSel=radVar.get() 91 | if radSel == 0: win.configure(background=colors[0]) # zero-based 92 | elif radSel == 1: win.configure(background=colors[1]) # using list 93 | elif radSel == 2: win.configure(background=colors[2]) 94 | 95 | # create three Radiobuttons using one variable 96 | radVar = tk.IntVar() 97 | 98 | # Next we are selecting a non-existing index value for radVar 99 | radVar.set(99) 100 | 101 | # Now we are creating all three Radiobutton widgets within one loop 102 | for col in range(3): 103 | curRad = tk.Radiobutton(win, text=colors[col], variable=radVar, 104 | value=col, command=radCall) 105 | curRad.grid(column=col, row=6, sticky=tk.W) # now row=6 106 | 107 | # Create a container to hold labels 108 | buttons_frame = ttk.LabelFrame(win, text=' Labels in a Frame ') 109 | buttons_frame.grid(column=0, row=7) 110 | 111 | # Place labels into the container element 112 | ttk.Label(buttons_frame, text="Label1").grid(column=0, row=0, sticky=tk.W) 113 | ttk.Label(buttons_frame, text="Label2").grid(column=1, row=0, sticky=tk.W) 114 | ttk.Label(buttons_frame, text="Label3").grid(column=2, row=0, sticky=tk.W) 115 | 116 | name_entered.focus() # Place cursor into name Entry 117 | #====================== 118 | # Start GUI 119 | #====================== 120 | win.mainloop() -------------------------------------------------------------------------------- /Chapter02/Ch02_Code/GUI_remove_sticky.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | from tkinter import scrolledtext 11 | 12 | # Create instance 13 | win = tk.Tk() 14 | 15 | # Add a title 16 | win.title("Python GUI") 17 | 18 | # Modify adding a Label 19 | a_label = ttk.Label(win, text="A Label") 20 | a_label.grid(column=0, row=0) 21 | 22 | # Modified Button Click Function 23 | def click_me(): 24 | action.configure(text='Hello ' + name.get() + ' ' + 25 | number_chosen.get()) 26 | 27 | # Changing our Label 28 | ttk.Label(win, text="Enter a name:").grid(column=0, row=0) 29 | 30 | # Adding a Textbox Entry widget 31 | name = tk.StringVar() 32 | name_entered = ttk.Entry(win, width=12, textvariable=name) 33 | name_entered.grid(column=0, row=1) 34 | 35 | # Adding a Button 36 | action = ttk.Button(win, text="Click Me!", command=click_me) 37 | action.grid(column=2, row=1) # <= change column to 2 38 | 39 | # Creating three checkbuttons 40 | ttk.Label(win, text="Choose a number:").grid(column=1, row=0) 41 | number = tk.StringVar() 42 | number_chosen = ttk.Combobox(win, width=12, textvariable=number, state='readonly') 43 | number_chosen['values'] = (1, 2, 4, 42, 100) 44 | number_chosen.grid(column=1, row=1) 45 | number_chosen.current(0) 46 | 47 | chVarDis = tk.IntVar() 48 | check1 = tk.Checkbutton(win, text="Disabled", variable=chVarDis, state='disabled') 49 | check1.select() 50 | check1.grid(column=0, row=4, sticky=tk.W) 51 | 52 | chVarUn = tk.IntVar() 53 | check2 = tk.Checkbutton(win, text="UnChecked", variable=chVarUn) 54 | check2.deselect() 55 | check2.grid(column=1, row=4, sticky=tk.W) 56 | 57 | chVarEn = tk.IntVar() 58 | check3 = tk.Checkbutton(win, text="Enabled", variable=chVarEn) 59 | check3.deselect() 60 | check3.grid(column=2, row=4, sticky=tk.W) 61 | 62 | # GUI Callback function 63 | def checkCallback(*ignoredArgs): 64 | # only enable one checkbutton 65 | if chVarUn.get(): check3.configure(state='disabled') 66 | else: check3.configure(state='normal') 67 | if chVarEn.get(): check2.configure(state='disabled') 68 | else: check2.configure(state='normal') 69 | 70 | # trace the state of the two checkbuttons 71 | chVarUn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 72 | chVarEn.trace('w', lambda unused0, unused1, unused2 : checkCallback()) 73 | 74 | 75 | # Using a scrolled Text control 76 | scrol_w = 30 77 | scrol_h = 3 78 | scr = scrolledtext.ScrolledText(win, width=scrol_w, height=scrol_h, wrap=tk.WORD) 79 | #### scr.grid(column=0, row=5, sticky='WE', columnspan=3) 80 | scr.grid(column=0, row=5, columnspan=3) # sticky property removed 81 | 82 | 83 | # First, we change our Radiobutton global variables into a list 84 | colors = ["Blue", "Gold", "Red"] 85 | 86 | # We have also changed the callback function to be zero-based, using the list 87 | # instead of module-level global variables 88 | # Radiobutton Callback 89 | def radCall(): 90 | radSel=radVar.get() 91 | if radSel == 0: win.configure(background=colors[0]) # zero-based 92 | elif radSel == 1: win.configure(background=colors[1]) # using list 93 | elif radSel == 2: win.configure(background=colors[2]) 94 | 95 | # create three Radiobuttons using one variable 96 | radVar = tk.IntVar() 97 | 98 | # Next we are selecting a non-existing index value for radVar 99 | radVar.set(99) 100 | 101 | # Now we are creating all three Radiobutton widgets within one loop 102 | for col in range(3): 103 | curRad = tk.Radiobutton(win, text=colors[col], variable=radVar, 104 | value=col, command=radCall) 105 | curRad.grid(column=col, row=6, sticky=tk.W) # now row=6 106 | 107 | # Create a container to hold labels 108 | buttons_frame = ttk.LabelFrame(win, text=' Labels in a Frame ') 109 | buttons_frame.grid(column=0, row=7) 110 | 111 | # Place labels into the container element 112 | ttk.Label(buttons_frame, text="Label1").grid(column=0, row=0, sticky=tk.W) 113 | ttk.Label(buttons_frame, text="Label2").grid(column=1, row=0, sticky=tk.W) 114 | ttk.Label(buttons_frame, text="Label3").grid(column=2, row=0, sticky=tk.W) 115 | 116 | name_entered.focus() # Place cursor into name Entry 117 | #====================== 118 | # Start GUI 119 | #====================== 120 | win.mainloop() -------------------------------------------------------------------------------- /Chapter02/Ch02_Code/GUI_tabbed.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | 11 | win = tk.Tk() # Create instance 12 | win.title("Python GUI") # Add a title 13 | tabControl = ttk.Notebook(win) # Create Tab Control 14 | tab1 = ttk.Frame(tabControl) # Create a tab 15 | tabControl.add(tab1, text='Tab 1') # Add the tab 16 | tabControl.pack(expand=1, fill="both") # Pack to make visible 17 | 18 | #====================== 19 | # Start GUI 20 | #====================== 21 | win.mainloop() 22 | -------------------------------------------------------------------------------- /Chapter02/Ch02_Code/GUI_tabbed_two.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | 11 | # Create instance 12 | win = tk.Tk() 13 | 14 | # Add a title 15 | win.title("Python GUI") 16 | 17 | tabControl = ttk.Notebook(win) # Create Tab Control 18 | 19 | tab1 = ttk.Frame(tabControl) # Create a tab 20 | tabControl.add(tab1, text='Tab 1') # Add the tab 21 | tab2 = ttk.Frame(tabControl) # Add a second tab 22 | tabControl.add(tab2, text='Tab 2') # Add second tab 23 | 24 | tabControl.pack(expand=1, fill="both") # Pack to make visible 25 | 26 | #====================== 27 | # Start GUI 28 | #====================== 29 | win.mainloop() 30 | -------------------------------------------------------------------------------- /Chapter02/Ch02_Code/GUI_tabbed_two_mighty.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | 11 | # Create instance 12 | win = tk.Tk() 13 | 14 | # Add a title 15 | win.title("Python GUI") 16 | 17 | tabControl = ttk.Notebook(win) # Create Tab Control 18 | 19 | tab1 = ttk.Frame(tabControl) # Create a tab 20 | tabControl.add(tab1, text='Tab 1') # Add the tab 21 | tab2 = ttk.Frame(tabControl) # Add a second tab 22 | tabControl.add(tab2, text='Tab 2') # Make second tab visible 23 | 24 | tabControl.pack(expand=1, fill="both") # Pack to make visible 25 | 26 | # LabelFrame using tab1 as the parent 27 | mighty = ttk.LabelFrame(tab1, text=' Mighty Python ') 28 | mighty.grid(column=0, row=0, padx=8, pady=4) 29 | 30 | # Label using mighty as the parent 31 | a_label = ttk.Label(mighty, text="Enter a name:") 32 | a_label.grid(column=0, row=0, sticky='W') 33 | 34 | 35 | #====================== 36 | # Start GUI 37 | #====================== 38 | win.mainloop() 39 | -------------------------------------------------------------------------------- /Chapter02/Ch02_Code/GUI_tabbed_two_mighty_labels.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | from tkinter import ttk 10 | 11 | # Create instance 12 | win = tk.Tk() 13 | 14 | # Add a title 15 | win.title("Python GUI") 16 | 17 | tabControl = ttk.Notebook(win) # Create Tab Control 18 | 19 | tab1 = ttk.Frame(tabControl) # Create a tab 20 | tabControl.add(tab1, text='Tab 1') # Add the tab 21 | tab2 = ttk.Frame(tabControl) # Add a second tab 22 | tabControl.add(tab2, text='Tab 2') # Make second tab visible 23 | 24 | tabControl.pack(expand=1, fill="both") # Pack to make visible 25 | 26 | # LabelFrame using tab1 as the parent 27 | mighty = ttk.LabelFrame(tab1, text=' Mighty Python ') 28 | mighty.grid(column=0, row=0, padx=8, pady=4) 29 | 30 | # Label using mighty as the parent 31 | a_label = ttk.Label(mighty, text="Enter a name:") 32 | a_label.grid(column=0, row=0, sticky='W') 33 | 34 | # Add another label 35 | ttk.Label(mighty, text="Choose a number:").grid(column=1, row=0) 36 | 37 | # Add some space around each label 38 | for child in mighty.winfo_children(): 39 | child.grid_configure(padx=8) 40 | 41 | #====================== 42 | # Start GUI 43 | #====================== 44 | win.mainloop() 45 | -------------------------------------------------------------------------------- /Chapter02/Ch02_Code/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Python-GUI-Programming-Cookbook-Second-Edition/1ca9866be88b4191a5a951cbc4ead7aad903f226/Chapter02/Ch02_Code/__init__.py -------------------------------------------------------------------------------- /Chapter03/Ch03_Code/GUI_independent_msg.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | 6 | from tkinter import messagebox as msg 7 | msg.showinfo('Python GUI created using tkinter:\nThe year is 2017') 8 | -------------------------------------------------------------------------------- /Chapter03/Ch03_Code/GUI_independent_msg_info.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | 6 | from tkinter import messagebox as msg 7 | msg.showinfo('Python GUI created using tkinter:\nThe year is 2017') 8 | 9 | # msg.showinfo('', 'Python GUI created using tkinter:\nThe year is 2017') -------------------------------------------------------------------------------- /Chapter03/Ch03_Code/GUI_independent_msg_one_window.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | 6 | from tkinter import messagebox as msg 7 | from tkinter import Tk 8 | root = Tk() 9 | root.withdraw() 10 | msg.showinfo('', 'Python GUI created using tkinter:\nThe year is 2017') 11 | -------------------------------------------------------------------------------- /Chapter03/Ch03_Code/GUI_independent_msg_one_window_title.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | 6 | from tkinter import messagebox as msg 7 | from tkinter import Tk 8 | root = Tk() 9 | root.withdraw() 10 | msg.showinfo('This is a Title', 'Python GUI created using tkinter:\nThe year is 2017') 11 | -------------------------------------------------------------------------------- /Chapter03/Ch03_Code/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Python-GUI-Programming-Cookbook-Second-Edition/1ca9866be88b4191a5a951cbc4ead7aad903f226/Chapter03/Ch03_Code/__init__.py -------------------------------------------------------------------------------- /Chapter03/Ch03_Code/pyc.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Python-GUI-Programming-Cookbook-Second-Edition/1ca9866be88b4191a5a951cbc4ead7aad903f226/Chapter03/Ch03_Code/pyc.ico -------------------------------------------------------------------------------- /Chapter04/Ch04_Code/GUI_PyDoubleVar_to_Float_Get.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | 9 | import tkinter as tk 10 | 11 | # Create instance of tkinter 12 | win = tk.Tk() 13 | 14 | # Create DoubleVar 15 | doubleData = tk.DoubleVar() 16 | print(doubleData.get()) # default value 17 | doubleData.set(2.4) 18 | print(type(doubleData)) 19 | 20 | add_doubles = 1.222222222222222222222222 + doubleData.get() 21 | print(add_doubles) 22 | print(type(add_doubles)) 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /Chapter04/Ch04_Code/GUI_PyVar_Get.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | 9 | import tkinter as tk 10 | 11 | # Create instance of tkinter 12 | win = tk.Tk() 13 | 14 | # Print out the default tkinter variable values 15 | intData = tk.IntVar() 16 | print(intData) 17 | print(intData.get()) 18 | 19 | # Set a breakpoint here to see the values in the debugger 20 | print() 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /Chapter04/Ch04_Code/GUI_PyVar_defaults.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | 9 | import tkinter as tk 10 | 11 | # Create instance of tkinter 12 | win = tk.Tk() 13 | 14 | # Assign tkinter Variable to strData variable 15 | strData = tk.StringVar() 16 | 17 | # Set strData variable 18 | strData.set('Hello StringVar') 19 | 20 | # Get value of strData variable 21 | varData = strData.get() 22 | 23 | # Print out current value of strData 24 | print(varData) 25 | 26 | # Print out the default tkinter variable values 27 | print(tk.IntVar()) 28 | print(tk.DoubleVar()) 29 | print(tk.BooleanVar()) 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /Chapter04/Ch04_Code/GUI_StringVar.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | 9 | import tkinter as tk 10 | 11 | # Create instance of tkinter 12 | win = tk.Tk() 13 | 14 | # Assign tkinter Variable to strData variable 15 | strData = tk.StringVar() 16 | 17 | # Set strData variable 18 | strData.set('Hello StringVar') 19 | 20 | # Get value of strData variable 21 | varData = strData.get() 22 | 23 | # Print out current value of strData 24 | print(varData) 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /Chapter04/Ch04_Code/ToolTip.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | 10 | #=================================================================== 11 | class ToolTip(object): 12 | def __init__(self, widget): 13 | self.widget = widget 14 | self.tip_window = None 15 | 16 | def show_tip(self, tip_text): 17 | "Display text in a tooltip window" 18 | if self.tip_window or not tip_text: 19 | return 20 | x, y, _cx, cy = self.widget.bbox("insert") # get size of widget 21 | x = x + self.widget.winfo_rootx() + 25 # calculate to display tooltip 22 | y = y + cy + self.widget.winfo_rooty() + 25 # below and to the right 23 | self.tip_window = tw = tk.Toplevel(self.widget) # create new tooltip window 24 | tw.wm_overrideredirect(True) # remove all Window Manager (wm) decorations 25 | # tw.wm_overrideredirect(False) # uncomment to see the effect 26 | tw.wm_geometry("+%d+%d" % (x, y)) # create window size 27 | 28 | label = tk.Label(tw, text=tip_text, justify=tk.LEFT, 29 | background="#ffffe0", relief=tk.SOLID, borderwidth=1, 30 | font=("tahoma", "8", "normal")) 31 | label.pack(ipadx=1) 32 | 33 | def hide_tip(self): 34 | tw = self.tip_window 35 | self.tip_window = None 36 | if tw: 37 | tw.destroy() 38 | 39 | #=================================================================== 40 | def create_ToolTip(widget, text): 41 | toolTip = ToolTip(widget) # create instance of class 42 | def enter(event): 43 | try: toolTip.show_tip(text) 44 | except: pass 45 | def leave(event): 46 | toolTip.hide_tip() 47 | widget.bind('', enter) # bind mouse events 48 | widget.bind('', leave) 49 | 50 | 51 | -------------------------------------------------------------------------------- /Chapter04/Ch04_Code/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Python-GUI-Programming-Cookbook-Second-Edition/1ca9866be88b4191a5a951cbc4ead7aad903f226/Chapter04/Ch04_Code/__init__.py -------------------------------------------------------------------------------- /Chapter04/Ch04_Code/pyc.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Python-GUI-Programming-Cookbook-Second-Edition/1ca9866be88b4191a5a951cbc4ead7aad903f226/Chapter04/Ch04_Code/pyc.ico -------------------------------------------------------------------------------- /Chapter05/Ch05_Code/Matplotlib_chart.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This code was downloaded from the official matplotlib.org website. 3 | It is one of the examples freely available on this website. 4 | It's name at the time of printing was: surface3d_demo.py 5 | ''' 6 | 7 | from mpl_toolkits.mplot3d import Axes3D #@UnresolvedImport 8 | from matplotlib import cm 9 | from matplotlib.ticker import LinearLocator, FormatStrFormatter 10 | import matplotlib.pyplot as plt 11 | import numpy as np 12 | 13 | fig = plt.figure() 14 | ax = fig.gca(projection='3d') 15 | X = np.arange(-5, 5, 0.25) 16 | Y = np.arange(-5, 5, 0.25) 17 | X, Y = np.meshgrid(X, Y) 18 | R = np.sqrt(X**2 + Y**2) 19 | Z = np.sin(R) 20 | surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False) #@UndefinedVariable 21 | ax.set_zlim(-1.01, 1.01) 22 | 23 | ax.zaxis.set_major_locator(LinearLocator(10)) 24 | ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) 25 | 26 | fig.colorbar(surf, shrink=0.5, aspect=5) 27 | 28 | plt.show() 29 | 30 | -------------------------------------------------------------------------------- /Chapter05/Ch05_Code/Matplotlib_chart_with_legend.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard 4 | ''' 5 | from matplotlib.figure import Figure 6 | from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg 7 | import tkinter as tk 8 | #-------------------------------------------------------------- 9 | fig = Figure(figsize=(12, 5), facecolor='white') 10 | #-------------------------------------------------------------- 11 | axis = fig.add_subplot(111) # 1 row, 1 column 12 | 13 | xValues = [1,2,3,4] 14 | 15 | yValues0 = [6,7.5,8,7.5] 16 | yValues1 = [5.5,6.5,8,6] 17 | yValues2 = [6.5,7,8,7] 18 | 19 | # the commas after t0, t1 and t2 are required 20 | t0, = axis.plot(xValues, yValues0) 21 | t1, = axis.plot(xValues, yValues1) 22 | t2, = axis.plot(xValues, yValues2) 23 | 24 | # t0, = axis.plot(xValues, yValues0, color = 'purple') # change the color of the plotted line to purple 25 | # t0, = axis.plot(xValues, yValues0, color = 'r') # change the color of the plotted line 26 | # t1, = axis.plot(xValues, yValues1, color = 'b') 27 | # t2, = axis.plot(xValues, yValues2, color = 'purple') 28 | 29 | axis.set_ylabel('Vertical Label') 30 | axis.set_xlabel('Horizontal Label') 31 | 32 | axis.grid() 33 | 34 | fig.legend((t0, t1, t2), ('First line', 'Second line', 'Third line'), 'upper right') 35 | 36 | #-------------------------------------------------------------- 37 | def _destroyWindow(): 38 | root.quit() 39 | root.destroy() 40 | #-------------------------------------------------------------- 41 | root = tk.Tk() 42 | root.withdraw() 43 | root.protocol('WM_DELETE_WINDOW', _destroyWindow) 44 | #-------------------------------------------------------------- 45 | canvas = FigureCanvasTkAgg(fig, master=root) 46 | canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1) 47 | #-------------------------------------------------------------- 48 | root.update() 49 | root.deiconify() 50 | root.mainloop() 51 | -------------------------------------------------------------------------------- /Chapter05/Ch05_Code/Matplotlib_chart_with_legend_missing_comma.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard 4 | ''' 5 | from matplotlib.figure import Figure 6 | from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg 7 | import tkinter as tk 8 | #-------------------------------------------------------------- 9 | fig = Figure(figsize=(12, 5), facecolor='white') 10 | #-------------------------------------------------------------- 11 | axis = fig.add_subplot(111) # 1 row, 1 column 12 | 13 | xValues = [1,2,3,4] 14 | 15 | yValues0 = [6,7.5,8,7.5] 16 | yValues1 = [5.5,6.5,8,6] 17 | yValues2 = [6.5,7,8,7] 18 | 19 | # the commas after t0, t1 and t2 are required 20 | t0 = axis.plot(xValues, yValues0) # no comma here 21 | t1, = axis.plot(xValues, yValues1) 22 | t2, = axis.plot(xValues, yValues2) 23 | 24 | # t0, = axis.plot(xValues, yValues0, color = 'purple') # change the color of the plotted line to purple 25 | # t0, = axis.plot(xValues, yValues0, color = 'r') # change the color of the plotted line 26 | # t1, = axis.plot(xValues, yValues1, color = 'b') 27 | # t2, = axis.plot(xValues, yValues2, color = 'purple') 28 | 29 | axis.set_ylabel('Vertical Label') 30 | axis.set_xlabel('Horizontal Label') 31 | 32 | axis.grid() 33 | 34 | fig.legend((t0, t1, t2), ('First line', 'Second line', 'Third line'), 'upper right') 35 | 36 | #-------------------------------------------------------------- 37 | def _destroyWindow(): 38 | root.quit() 39 | root.destroy() 40 | #-------------------------------------------------------------- 41 | root = tk.Tk() 42 | root.withdraw() 43 | root.protocol('WM_DELETE_WINDOW', _destroyWindow) 44 | #-------------------------------------------------------------- 45 | canvas = FigureCanvasTkAgg(fig, master=root) 46 | canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1) 47 | #-------------------------------------------------------------- 48 | root.update() 49 | root.deiconify() 50 | root.mainloop() 51 | -------------------------------------------------------------------------------- /Chapter05/Ch05_Code/Matplotlib_labels.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | 6 | from matplotlib.figure import Figure 7 | from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg 8 | import tkinter as tk 9 | #-------------------------------------------------------------- 10 | fig = Figure(figsize=(12, 8), facecolor='white') 11 | #-------------------------------------------------------------- 12 | # axis = fig.add_subplot(111) # 1 row, 1 column, only graph 13 | axis = fig.add_subplot(211) # 2 rows, 1 column, Top graph 14 | #-------------------------------------------------------------- 15 | xValues = [1,2,3,4] 16 | yValues = [5,7,6,8] 17 | axis.plot(xValues, yValues) 18 | 19 | axis.set_xlabel('Horizontal Label') 20 | axis.set_ylabel('Vertical Label') 21 | 22 | # axis.grid() # default line style 23 | axis.grid(linestyle='-') # solid grid lines 24 | #-------------------------------------------------------------- 25 | def _destroyWindow(): 26 | root.quit() 27 | root.destroy() 28 | #-------------------------------------------------------------- 29 | root = tk.Tk() 30 | root.withdraw() 31 | root.protocol('WM_DELETE_WINDOW', _destroyWindow) 32 | #-------------------------------------------------------------- 33 | canvas = FigureCanvasTkAgg(fig, master=root) 34 | canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1) 35 | #-------------------------------------------------------------- 36 | root.update() 37 | root.deiconify() 38 | root.mainloop() 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /Chapter05/Ch05_Code/Matplotlib_labels_four.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | 6 | from matplotlib.figure import Figure 7 | from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg 8 | import tkinter as tk 9 | #-------------------------------------------------------------- 10 | fig = Figure(figsize=(12, 8), facecolor='white') 11 | xValues = [1,2,3,4] 12 | yValues = [5,7,6,8] 13 | #-------------------------------------------------------------- 14 | axis1 = fig.add_subplot(221) 15 | axis2 = fig.add_subplot(222, sharex=axis1, sharey=axis1) 16 | axis3 = fig.add_subplot(223, sharex=axis1, sharey=axis1) 17 | axis4 = fig.add_subplot(224, sharex=axis1, sharey=axis1) 18 | #-------------------------------------------------------------- 19 | axis1.plot(xValues, yValues) 20 | axis1.set_xlabel('Horizontal Label 1') 21 | axis1.set_ylabel('Vertical Label 1') 22 | axis1.grid(linestyle='-') # solid grid lines 23 | #-------------------------------------------------------------- 24 | axis2.plot(xValues, yValues) 25 | axis2.set_xlabel('Horizontal Label 2') 26 | axis2.set_ylabel('Vertical Label 2') 27 | axis2.grid(linestyle='-') # solid grid lines 28 | #-------------------------------------------------------------- 29 | axis3.plot(xValues, yValues) 30 | axis3.set_xlabel('Horizontal Label3') 31 | axis3.set_ylabel('Vertical Label 3') 32 | axis3.grid(linestyle='-') # solid grid lines 33 | #-------------------------------------------------------------- 34 | axis4.plot(xValues, yValues) 35 | axis4.set_xlabel('Horizontal Label 4') 36 | axis4.set_ylabel('Vertical Label 4') 37 | axis4.grid(linestyle='-') # solid grid lines 38 | #-------------------------------------------------------------- 39 | 40 | #-------------------------------------------------------------- 41 | def _destroyWindow(): 42 | root.quit() 43 | root.destroy() 44 | #-------------------------------------------------------------- 45 | root = tk.Tk() 46 | root.withdraw() 47 | root.protocol('WM_DELETE_WINDOW', _destroyWindow) 48 | #-------------------------------------------------------------- 49 | canvas = FigureCanvasTkAgg(fig, master=root) 50 | canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1) 51 | #-------------------------------------------------------------- 52 | root.update() 53 | root.deiconify() 54 | root.mainloop() 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /Chapter05/Ch05_Code/Matplotlib_labels_two_charts.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard 4 | ''' 5 | from matplotlib.figure import Figure 6 | from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg 7 | import tkinter as tk 8 | #-------------------------------------------------------------- 9 | fig = Figure(figsize=(12, 8), facecolor='white') 10 | #-------------------------------------------------------------- 11 | axis = fig.add_subplot(211) # 2 rows, 1 column, Top graph 12 | #-------------------------------------------------------------- 13 | xValues = [1,2,3,4] 14 | yValues0 = [5,7,6,8] 15 | axis.plot(xValues, yValues0) 16 | 17 | axis.set_xlabel('Horizontal Label') 18 | axis.set_ylabel('Vertical Label') 19 | 20 | axis.grid(linestyle='-') # solid grid lines 21 | #-------------------------------------------------------------- 22 | axis1 = fig.add_subplot(212) # 2 rows, 1 column, Bottom graph 23 | #-------------------------------------------------------------- 24 | xValues1 = [1,2,3,4] 25 | yValues1 = [7,5,8,6] 26 | axis1.plot(xValues1, yValues1) 27 | axis1.grid() # default line style 28 | #-------------------------------------------------------------- 29 | def _destroyWindow(): 30 | root.quit() 31 | root.destroy() 32 | #-------------------------------------------------------------- 33 | root = tk.Tk() 34 | root.withdraw() 35 | root.protocol('WM_DELETE_WINDOW', _destroyWindow) 36 | #-------------------------------------------------------------- 37 | canvas = FigureCanvasTkAgg(fig, master=root) 38 | canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1) 39 | #-------------------------------------------------------------- 40 | root.update() 41 | root.deiconify() 42 | root.mainloop() 43 | -------------------------------------------------------------------------------- /Chapter05/Ch05_Code/Matplotlib_labels_two_charts_not_scaled.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard 4 | ''' 5 | from matplotlib.figure import Figure 6 | from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg 7 | import tkinter as tk 8 | #-------------------------------------------------------------- 9 | fig = Figure(figsize=(12, 5), facecolor='white') 10 | #-------------------------------------------------------------- 11 | axis = fig.add_subplot(111) # 1 row, 1 column 12 | 13 | xValues = [1,2,3,4] 14 | 15 | yValues0 = [6,7.5,8,7.5] 16 | yValues1 = [5.5,6.5,50,6] # one very high value (50) 17 | yValues2 = [6.5,7,8,7] 18 | 19 | # axis.set_ylim(5, 8) # limit the vertical display 20 | 21 | t0, = axis.plot(xValues, yValues0) 22 | t1, = axis.plot(xValues, yValues1) 23 | t2, = axis.plot(xValues, yValues2) 24 | 25 | axis.set_ylabel('Vertical Label') 26 | axis.set_xlabel('Horizontal Label') 27 | 28 | axis.grid() 29 | 30 | fig.legend((t0, t1, t2), ('First line', 'Second line', 'Third line'), 'upper right') 31 | 32 | #-------------------------------------------------------------- 33 | def _destroyWindow(): 34 | root.quit() 35 | root.destroy() 36 | #-------------------------------------------------------------- 37 | root = tk.Tk() 38 | root.withdraw() 39 | root.protocol('WM_DELETE_WINDOW', _destroyWindow) 40 | #-------------------------------------------------------------- 41 | canvas = FigureCanvasTkAgg(fig, master=root) 42 | canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1) 43 | #-------------------------------------------------------------- 44 | root.update() 45 | root.deiconify() 46 | root.mainloop() 47 | -------------------------------------------------------------------------------- /Chapter05/Ch05_Code/Matplotlib_labels_two_charts_scaled.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard 4 | ''' 5 | from matplotlib.figure import Figure 6 | from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg 7 | import tkinter as tk 8 | #-------------------------------------------------------------- 9 | fig = Figure(figsize=(12, 5), facecolor='white') 10 | #-------------------------------------------------------------- 11 | axis = fig.add_subplot(111) # 1 row, 1 column 12 | 13 | xValues = [1,2,3,4] 14 | 15 | yValues0 = [6,7.5,8,7.5] 16 | yValues1 = [5.5,6.5,50,6] # one very high value (50) 17 | yValues2 = [6.5,7,8,7] 18 | 19 | axis.set_ylim(5, 8) # limit the vertical display 20 | 21 | t0, = axis.plot(xValues, yValues0) 22 | t1, = axis.plot(xValues, yValues1) 23 | t2, = axis.plot(xValues, yValues2) 24 | 25 | axis.set_ylabel('Vertical Label') 26 | axis.set_xlabel('Horizontal Label') 27 | 28 | axis.grid() 29 | 30 | fig.legend((t0, t1, t2), ('First line', 'Second line', 'Third line'), 'upper right') 31 | 32 | #-------------------------------------------------------------- 33 | def _destroyWindow(): 34 | root.quit() 35 | root.destroy() 36 | #-------------------------------------------------------------- 37 | root = tk.Tk() 38 | root.withdraw() 39 | root.protocol('WM_DELETE_WINDOW', _destroyWindow) 40 | #-------------------------------------------------------------- 41 | canvas = FigureCanvasTkAgg(fig, master=root) 42 | canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1) 43 | #-------------------------------------------------------------- 44 | root.update() 45 | root.deiconify() 46 | root.mainloop() 47 | -------------------------------------------------------------------------------- /Chapter05/Ch05_Code/Matplotlib_labels_two_charts_scaled_dynamic.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard 4 | ''' 5 | from matplotlib.figure import Figure 6 | from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg 7 | import tkinter as tk 8 | #-------------------------------------------------------------- 9 | fig = Figure(figsize=(12, 5), facecolor='white') 10 | #-------------------------------------------------------------- 11 | axis = fig.add_subplot(111) # 1 row, 1 column 12 | 13 | xValues = [1,2,3,4] 14 | 15 | yValues0 = [6,7.5,8,7.5] 16 | yValues1 = [5.5,6.5,50,6] # one very high value (50) 17 | yValues2 = [6.5,7,8,7] 18 | yAll = [yValues0, yValues1, yValues2] # list of lists 19 | 20 | # flatten list of lists retrieving minimum value 21 | minY = min([y for yValues in yAll for y in yValues]) 22 | 23 | yUpperLimit = 20 24 | # flatten list of lists retrieving max value within defined limit 25 | maxY = max([y for yValues in yAll for y in yValues if y < yUpperLimit]) 26 | 27 | # dynamic limits 28 | axis.set_ylim(minY, maxY) 29 | axis.set_xlim(min(xValues), max(xValues)) 30 | 31 | t0, = axis.plot(xValues, yValues0) 32 | t1, = axis.plot(xValues, yValues1) 33 | t2, = axis.plot(xValues, yValues2) 34 | 35 | axis.set_ylabel('Vertical Label') 36 | axis.set_xlabel('Horizontal Label') 37 | 38 | axis.grid() 39 | fig.legend((t0, t1, t2), ('First line', 'Second line', 'Third line'), 'upper right') 40 | #-------------------------------------------------------------- 41 | def _destroyWindow(): 42 | root.quit() 43 | root.destroy() 44 | #-------------------------------------------------------------- 45 | root = tk.Tk() 46 | root.withdraw() 47 | root.protocol('WM_DELETE_WINDOW', _destroyWindow) 48 | #-------------------------------------------------------------- 49 | canvas = FigureCanvasTkAgg(fig, master=root) 50 | canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1) 51 | #-------------------------------------------------------------- 52 | root.update() 53 | root.deiconify() 54 | root.mainloop() 55 | -------------------------------------------------------------------------------- /Chapter05/Ch05_Code/Matplotlib_labels_two_charts_scaled_dynamic_spike.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard 4 | ''' 5 | from matplotlib.figure import Figure 6 | from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg 7 | import tkinter as tk 8 | #-------------------------------------------------------------- 9 | fig = Figure(figsize=(12, 5), facecolor='white') 10 | #-------------------------------------------------------------- 11 | axis = fig.add_subplot(111) # 1 row, 1 column 12 | 13 | xValues = [1,2,3,4] 14 | 15 | yValues0 = [6,7.5,8,7.5] 16 | yValues1 = [5.5,6.5,50,6] # one very high value (50) 17 | yValues2 = [6.5,7,8,7] 18 | 19 | axis.set_ylim(0, 8) # lower limit (0) 20 | axis.set_xlim(0, 8) # use same limits for x 21 | 22 | t0, = axis.plot(xValues, yValues0) 23 | t1, = axis.plot(xValues, yValues1) 24 | t2, = axis.plot(xValues, yValues2) 25 | 26 | axis.set_ylabel('Vertical Label') 27 | axis.set_xlabel('Horizontal Label') 28 | 29 | axis.grid() 30 | fig.legend((t0, t1, t2), ('First line', 'Second line', 'Third line'), 'upper right') 31 | #-------------------------------------------------------------- 32 | def _destroyWindow(): 33 | root.quit() 34 | root.destroy() 35 | #-------------------------------------------------------------- 36 | root = tk.Tk() 37 | root.withdraw() 38 | root.protocol('WM_DELETE_WINDOW', _destroyWindow) 39 | #-------------------------------------------------------------- 40 | canvas = FigureCanvasTkAgg(fig, master=root) 41 | canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1) 42 | #-------------------------------------------------------------- 43 | root.update() 44 | root.deiconify() 45 | root.mainloop() 46 | -------------------------------------------------------------------------------- /Chapter05/Ch05_Code/Matplotlib_our_first_chart.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard 4 | ''' 5 | 6 | import numpy as np 7 | import matplotlib.pyplot as plt 8 | from pylab import show 9 | 10 | x = np.arange(0, 5, 0.1); 11 | y = np.sin(x) 12 | plt.plot(x, y) 13 | 14 | show() # call show() 15 | -------------------------------------------------------------------------------- /Chapter05/Ch05_Code/Matplotlib_second_chart.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard 4 | ''' 5 | 6 | from pylab import show, arange, sin, plot, pi 7 | 8 | t = arange(0.0, 2.0, 0.01) 9 | s = sin( 2 * pi * t ) 10 | plot(t, s) 11 | 12 | show() 13 | -------------------------------------------------------------------------------- /Chapter05/Ch05_Code/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Python-GUI-Programming-Cookbook-Second-Edition/1ca9866be88b4191a5a951cbc4ead7aad903f226/Chapter05/Ch05_Code/__init__.py -------------------------------------------------------------------------------- /Chapter06/Ch06_Code/Queues.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | 6 | # def write_to_scrol(inst): 7 | # print('hi from Queue', inst) 8 | # for idx in range(10): 9 | # inst.gui_queue.put('Message from a queue: ' + str(idx)) 10 | # inst.create_thread(6) 11 | 12 | 13 | # using TCP/IP 14 | from socket import socket, AF_INET, SOCK_STREAM 15 | 16 | def write_to_scrol(inst): 17 | print('hi from Queue', inst) 18 | sock = socket(AF_INET, SOCK_STREAM) 19 | sock.connect(('localhost', 24000)) 20 | for idx in range(10): 21 | sock.send(b'Message from a queue: ' + bytes(str(idx).encode()) ) 22 | recv = sock.recv(8192).decode() 23 | inst.gui_queue.put(recv) 24 | inst.create_thread(6) 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /Chapter06/Ch06_Code/TCP_Server.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard 4 | ''' 5 | 6 | from socketserver import BaseRequestHandler, TCPServer 7 | 8 | class RequestHandler(BaseRequestHandler): 9 | # override base class handle method 10 | def handle(self): 11 | print('Server connected to: ', self.client_address) 12 | while True: 13 | rsp = self.request.recv(512) 14 | if not rsp: break 15 | self.request.send(b'Server received: ' + rsp) 16 | 17 | def start_server(): 18 | server = TCPServer(('localhost', 24000), RequestHandler) 19 | server.serve_forever() 20 | 21 | 22 | # TODO: Implement stop server. Check if running before starting the server. 23 | # I leave this as an exercise for the reader. 24 | -------------------------------------------------------------------------------- /Chapter06/Ch06_Code/ToolTip.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | 10 | #=================================================================== 11 | class ToolTip(object): 12 | def __init__(self, widget): 13 | self.widget = widget 14 | self.tip_window = None 15 | 16 | def show_tip(self, tip_text): 17 | "Display text in a tooltip window" 18 | if self.tip_window or not tip_text: 19 | return 20 | x, y, _cx, cy = self.widget.bbox("insert") # get size of widget 21 | x = x + self.widget.winfo_rootx() + 25 # calculate to display tooltip 22 | y = y + cy + self.widget.winfo_rooty() + 25 # below and to the right 23 | self.tip_window = tw = tk.Toplevel(self.widget) # create new tooltip window 24 | tw.wm_overrideredirect(True) # remove all Window Manager (wm) decorations 25 | # tw.wm_overrideredirect(False) # uncomment to see the effect 26 | tw.wm_geometry("+%d+%d" % (x, y)) # create window size 27 | 28 | label = tk.Label(tw, text=tip_text, justify=tk.LEFT, 29 | background="#ffffe0", relief=tk.SOLID, borderwidth=1, 30 | font=("tahoma", "8", "normal")) 31 | label.pack(ipadx=1) 32 | 33 | def hide_tip(self): 34 | tw = self.tip_window 35 | self.tip_window = None 36 | if tw: 37 | tw.destroy() 38 | 39 | #=================================================================== 40 | def create_ToolTip(widget, text): 41 | toolTip = ToolTip(widget) # create instance of class 42 | def enter(event): 43 | try: toolTip.show_tip(text) 44 | except: pass 45 | def leave(event): 46 | toolTip.hide_tip() 47 | widget.bind('', enter) # bind mouse events 48 | widget.bind('', leave) 49 | 50 | 51 | -------------------------------------------------------------------------------- /Chapter06/Ch06_Code/URL.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | 6 | from urllib.request import urlopen 7 | link = 'http://python.org/' 8 | 9 | def get_html(): 10 | try: 11 | http_rsp = urlopen(link) 12 | print(http_rsp) 13 | html = http_rsp.read() 14 | print(html) 15 | html_decoded = html.decode() 16 | print(html_decoded) 17 | except Exception as ex: 18 | print('*** Failed to get Html! ***\n\n' + str(ex)) 19 | else: 20 | return html_decoded 21 | 22 | #------------------------------- 23 | if __name__ == '__main__': 24 | get_html() -------------------------------------------------------------------------------- /Chapter06/Ch06_Code/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Python-GUI-Programming-Cookbook-Second-Edition/1ca9866be88b4191a5a951cbc4ead7aad903f226/Chapter06/Ch06_Code/__init__.py -------------------------------------------------------------------------------- /Chapter06/Ch06_Code/pyc.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Python-GUI-Programming-Cookbook-Second-Edition/1ca9866be88b4191a5a951cbc4ead7aad903f226/Chapter06/Ch06_Code/pyc.ico -------------------------------------------------------------------------------- /Chapter07/Ch07_Code/GuiDBConfig.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | 6 | 7 | # create dictionary to hold connection info 8 | dbConfig = { 9 | 'user': 'Burkhard', 10 | 'password': 'Python', 11 | 'host': '127.0.0.1', 12 | } 13 | 14 | 15 | # # create dictionary to hold connection info 16 | # dbConfig = { 17 | # 'user': , # your user name 18 | # 'password': , # your password 19 | # 'host': '127.0.0.1', 20 | # } 21 | 22 | -------------------------------------------------------------------------------- /Chapter07/Ch07_Code/MySQL_connect.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | 6 | import MySQLdb as mysql 7 | conn = mysql.connect(user=, password=, host='127.0.0.1') 8 | print(conn) 9 | conn.close() 10 | -------------------------------------------------------------------------------- /Chapter07/Ch07_Code/MySQL_connect_import_dict.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | 6 | import MySQLdb as mysql 7 | import Ch07_Code.GuiDBConfig as guiConf 8 | 9 | # unpack dictionary credentials 10 | conn = mysql.connect(**guiConf.dbConfig) 11 | print(conn) -------------------------------------------------------------------------------- /Chapter07/Ch07_Code/MySQL_connect_with_dict.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | 6 | import MySQLdb as mysql 7 | 8 | # create dictionary to hold connection info 9 | dbConfig = { 10 | 'user': , # your user name 11 | 'password': , # your password 12 | 'host': '127.0.0.1', 13 | } 14 | 15 | conn = mysql.connect(**dbConfig) 16 | print(conn) 17 | conn.close() 18 | -------------------------------------------------------------------------------- /Chapter07/Ch07_Code/MySQL_create_DB.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | 6 | import MySQLdb as mysql 7 | import Ch07_Code.GuiDBConfig as guiConf 8 | 9 | GUIDB = 'GuiDB' 10 | 11 | # unpack dictionary credentials 12 | conn = mysql.connect(**guiConf.dbConfig) 13 | 14 | cursor = conn.cursor() 15 | 16 | try: 17 | cursor.execute("CREATE DATABASE {} \ 18 | DEFAULT CHARACTER SET 'utf8'".format(GUIDB)) 19 | 20 | except mysql.Error as err: # @UndefinedVariable 21 | print("Failed to create DB: {}".format(err)) 22 | 23 | conn.close() -------------------------------------------------------------------------------- /Chapter07/Ch07_Code/MySQL_show_DBs.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | 6 | import MySQLdb as mysql 7 | import Ch07_Code.GuiDBConfig as guiConf 8 | 9 | GUIDB = 'GuiDB' 10 | 11 | # unpack dictionary credentials 12 | conn = mysql.connect(**guiConf.dbConfig) 13 | 14 | cursor = conn.cursor() 15 | 16 | cursor.execute("SHOW DATABASES") 17 | print(cursor.fetchall()) 18 | 19 | conn.close() -------------------------------------------------------------------------------- /Chapter07/Ch07_Code/ToolTip.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | 10 | #=================================================================== 11 | class ToolTip(object): 12 | def __init__(self, widget): 13 | self.widget = widget 14 | self.tip_window = None 15 | 16 | def show_tip(self, tip_text): 17 | "Display text in a tooltip window" 18 | if self.tip_window or not tip_text: 19 | return 20 | x, y, _cx, cy = self.widget.bbox("insert") # get size of widget 21 | x = x + self.widget.winfo_rootx() + 25 # calculate to display tooltip 22 | y = y + cy + self.widget.winfo_rooty() + 25 # below and to the right 23 | self.tip_window = tw = tk.Toplevel(self.widget) # create new tooltip window 24 | tw.wm_overrideredirect(True) # remove all Window Manager (wm) decorations 25 | # tw.wm_overrideredirect(False) # uncomment to see the effect 26 | tw.wm_geometry("+%d+%d" % (x, y)) # create window size 27 | 28 | label = tk.Label(tw, text=tip_text, justify=tk.LEFT, 29 | background="#ffffe0", relief=tk.SOLID, borderwidth=1, 30 | font=("tahoma", "8", "normal")) 31 | label.pack(ipadx=1) 32 | 33 | def hide_tip(self): 34 | tw = self.tip_window 35 | self.tip_window = None 36 | if tw: 37 | tw.destroy() 38 | 39 | #=================================================================== 40 | def create_ToolTip(widget, text): 41 | toolTip = ToolTip(widget) # create instance of class 42 | def enter(event): 43 | try: toolTip.show_tip(text) 44 | except: pass 45 | def leave(event): 46 | toolTip.hide_tip() 47 | widget.bind('', enter) # bind mouse events 48 | widget.bind('', leave) 49 | 50 | 51 | -------------------------------------------------------------------------------- /Chapter07/Ch07_Code/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Python-GUI-Programming-Cookbook-Second-Edition/1ca9866be88b4191a5a951cbc4ead7aad903f226/Chapter07/Ch07_Code/__init__.py -------------------------------------------------------------------------------- /Chapter07/Ch07_Code/pyc.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Python-GUI-Programming-Cookbook-Second-Edition/1ca9866be88b4191a5a951cbc4ead7aad903f226/Chapter07/Ch07_Code/pyc.ico -------------------------------------------------------------------------------- /Chapter08/Ch08_Code/LanguageResources.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard 4 | ''' 5 | 6 | class I18N(): 7 | '''Internationalization''' 8 | def __init__(self, language): 9 | if language == 'en': self.resourceLanguageEnglish() 10 | elif language == 'de': self.resourceLanguageGerman() 11 | else: raise NotImplementedError('Unsupported language.') 12 | 13 | def resourceLanguageEnglish(self): 14 | self.title = "Python Graphical User Interface" 15 | 16 | self.file = "File" 17 | self.new = "New" 18 | self.exit = "Exit" 19 | self.help = "Help" 20 | self.about = "About" 21 | 22 | self.WIDGET_LABEL = ' Widgets Frame ' 23 | 24 | self.disabled = "Disabled" 25 | self.unChecked = "UnChecked" 26 | self.toggle = "Toggle" 27 | 28 | # Radiobutton list 29 | self.colors = ["Blue", "Gold", "Red"] 30 | self.colorsIn = ["in Blue", "in Gold", "in Red"] 31 | 32 | self.labelsFrame = ' Labels within a Frame ' 33 | self.chooseNumber = "Choose a number:" 34 | self.label2 = "Label 2" 35 | 36 | self.timeZones = "All Time Zones" 37 | self.localZone = "Local Zone" 38 | self.getTime = "New York" 39 | 40 | self.mgrFiles = ' Manage Files ' 41 | 42 | self.browseTo = "Browse to File..." 43 | self.copyTo = "Copy File To : " 44 | 45 | 46 | def resourceLanguageGerman(self): 47 | self.title = 'Python Grafische Benutzeroberflaeche' # w/out umlaut 48 | # self.title = 'Python Grafische Benutzeroberfl' + "\u00E4" + 'che' # with umlaut via Unicode 49 | self.title = 'Python Grafische Benutzeroberfläche' # with umlaut UTF-8 50 | 51 | self.file = "Datei" 52 | self.new = "Neu" 53 | self.exit = "Schliessen" 54 | self.help = "Hilfe" 55 | self.about = "\u00DC" + "ber" 56 | self.about = "Über" 57 | 58 | self.WIDGET_LABEL = ' Widgets Rahmen ' 59 | 60 | self.disabled = "Deaktiviert" 61 | self.unChecked = "Nicht Markiert" 62 | self.toggle = "Markieren" 63 | 64 | # Radiobutton list 65 | self.colors = ["Blau", "Gold", "Rot"] 66 | self.colorsIn = ["in Blau", "in Gold", "in Rot"] 67 | 68 | self.labelsFrame = ' Etiketten im Rahmen ' 69 | self.chooseNumber = "Waehle eine Nummer:" 70 | self.label2 = "Etikette 2" 71 | 72 | self.timeZones = "Alle Zeitzonen" 73 | self.localZone = "Lokale Zone" 74 | self.getTime = "Zeit" 75 | 76 | self.mgrFiles = ' Dateien Organisieren ' 77 | 78 | self.browseTo = "Waehle eine Datei... " 79 | self.copyTo = "Kopiere Datei zu : " 80 | 81 | #================================================= 82 | if __name__ == '__main__': 83 | language = 'en' 84 | inst = I18N(language) 85 | print(inst.title) 86 | 87 | language = 'de' 88 | inst = I18N(language) 89 | print(inst.title) 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | -------------------------------------------------------------------------------- /Chapter08/Ch08_Code/Logger.py: -------------------------------------------------------------------------------- 1 | import os, time 2 | from datetime import datetime 3 | 4 | class LogLevel: 5 | '''Define logging levels.''' 6 | OFF = 0 7 | MINIMUM = 1 8 | NORMAL = 2 9 | DEBUG = 3 10 | 11 | 12 | class Logger: 13 | ''' Create a test log and write to it. ''' 14 | #-------------------------------------------------------------------------- 15 | def __init__(self, fullTestName, loglevel=LogLevel.DEBUG): 16 | testName = os.path.splitext(os.path.basename(fullTestName))[0] 17 | logName = testName + '.log' 18 | 19 | logsFolder = 'logs' 20 | if not os.path.exists(logsFolder): 21 | os.makedirs(logsFolder, exist_ok = True) 22 | 23 | self.log = os.path.join(logsFolder, logName) 24 | self.createLog() 25 | 26 | self.loggingLevel = loglevel 27 | self.startTime = time.perf_counter() 28 | 29 | #-------------------------------------------------------------------------- 30 | def createLog(self): 31 | with open(self.log, mode='w', encoding='utf-8') as logFile: 32 | logFile.write(self.getDateTime() + 33 | '\t\t*** Starting Test ***\n') 34 | logFile.close() 35 | 36 | #-------------------------------------------------------------------------- 37 | def setLoggingLevel(self, level): 38 | '''change logging level in the middle of a test.''' 39 | self.loggingLevel = level 40 | 41 | #-------------------------------------------------------------------------- 42 | def writeToLog(self, msg='', loglevel=LogLevel.DEBUG): 43 | # control how much gets logged 44 | if loglevel > self.loggingLevel: 45 | return 46 | 47 | # open log file in append mode 48 | with open(self.log, mode='a', encoding='utf-8') as logFile: 49 | msg = str(msg) 50 | if msg.startswith('\n'): 51 | msg = msg[1:] 52 | logFile.write(self.getDateTime() + '\t\t' + msg + '\n') 53 | 54 | logFile.close() 55 | 56 | #-------------------------------------------------------------------------- 57 | def getDateTime(self,): 58 | return datetime.now().strftime("%Y-%m-%d %H:%M:%S") 59 | 60 | #-------------------------------------------------------------------------- 61 | def writeTestRunTime(self): 62 | elapsed = time.perf_counter() - self.startTime 63 | self.writeToLog('\nElapsed Test Time (seconds): {0:.2f}'.format(elapsed), loglevel=LogLevel.OFF) 64 | 65 | -------------------------------------------------------------------------------- /Chapter08/Ch08_Code/ToolTip.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | #====================== 6 | # imports 7 | #====================== 8 | import tkinter as tk 9 | 10 | #=================================================================== 11 | class ToolTip(object): 12 | def __init__(self, widget): 13 | self.widget = widget 14 | self.tip_window = None 15 | 16 | def show_tip(self, tip_text): 17 | "Display text in a tooltip window" 18 | if self.tip_window or not tip_text: 19 | return 20 | x, y, _cx, cy = self.widget.bbox("insert") # get size of widget 21 | x = x + self.widget.winfo_rootx() + 25 # calculate to display tooltip 22 | y = y + cy + self.widget.winfo_rooty() + 25 # below and to the right 23 | self.tip_window = tw = tk.Toplevel(self.widget) # create new tooltip window 24 | tw.wm_overrideredirect(True) # remove all Window Manager (wm) decorations 25 | # tw.wm_overrideredirect(False) # uncomment to see the effect 26 | tw.wm_geometry("+%d+%d" % (x, y)) # create window size 27 | 28 | label = tk.Label(tw, text=tip_text, justify=tk.LEFT, 29 | background="#ffffe0", relief=tk.SOLID, borderwidth=1, 30 | font=("tahoma", "8", "normal")) 31 | label.pack(ipadx=1) 32 | 33 | def hide_tip(self): 34 | tw = self.tip_window 35 | self.tip_window = None 36 | if tw: 37 | tw.destroy() 38 | 39 | #=================================================================== 40 | def create_ToolTip(widget, text): 41 | toolTip = ToolTip(widget) # create instance of class 42 | def enter(event): 43 | try: toolTip.show_tip(text) 44 | except: pass 45 | def leave(event): 46 | toolTip.hide_tip() 47 | widget.bind('', enter) # bind mouse events 48 | widget.bind('', leave) 49 | 50 | 51 | -------------------------------------------------------------------------------- /Chapter08/Ch08_Code/UnitTests.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard 4 | ''' 5 | 6 | import unittest 7 | from Ch08_Code.LanguageResources import I18N 8 | from Ch08_Code.GUI_Refactored import OOP as GUI 9 | 10 | class GuiUnitTests(unittest.TestCase): 11 | 12 | def test_TitleIsEnglish(self): 13 | i18n = I18N('en') 14 | self.assertEqual(i18n.title, "Python Graphical User Interface") 15 | 16 | def test_TitleIsGerman(self): 17 | # i18n = I18N('en') # <= Bug in Unit Test 18 | i18n = I18N('de') 19 | self.assertEqual(i18n.title, 'Python Grafische Benutzeroberfl' + "\u00E4" + 'che') 20 | 21 | 22 | class WidgetsTestsEnglish(unittest.TestCase): 23 | 24 | def setUp(self): 25 | self.gui = GUI('en') 26 | 27 | def tearDown(self): 28 | self.gui = None 29 | 30 | def test_WidgetLabels(self): 31 | self.assertEqual(self.gui.i18n.file, "File") 32 | self.assertEqual(self.gui.i18n.mgrFiles, ' Manage Files ') 33 | self.assertEqual(self.gui.i18n.browseTo, "Browse to File...") 34 | 35 | def test_LabelFrameText(self): 36 | labelFrameText = self.gui.widgetFrame['text'] 37 | self.assertEqual(labelFrameText, " Widgets Frame ") 38 | 39 | 40 | class WidgetsTestsGerman(unittest.TestCase): 41 | 42 | def setUp(self): 43 | self.gui = GUI('de') 44 | 45 | def test_WidgetLabels(self): 46 | self.assertEqual(self.gui.i18n.file, "Datei") 47 | self.assertEqual(self.gui.i18n.mgrFiles, ' Dateien Organisieren ') 48 | self.assertEqual(self.gui.i18n.browseTo, "Waehle eine Datei... ") 49 | 50 | def test_LabelFrameText(self): 51 | labelFrameText = self.gui.widgetFrame['text'] 52 | self.assertEqual(labelFrameText, " Widgets Rahmen ") 53 | self.gui.radVar.set(1) 54 | self.gui.callBacks.radCall() 55 | labelFrameText = self.gui.widgetFrame['text'] 56 | self.assertEqual(labelFrameText, 57 | " Widgets Rahmen in Gold") 58 | 59 | 60 | #========================== 61 | if __name__ == '__main__': 62 | unittest.main() 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /Chapter08/Ch08_Code/UnitTestsEnglish.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard 4 | ''' 5 | 6 | import unittest 7 | from Ch08_Code.LanguageResources import I18N 8 | from Ch08_Code.GUI_Refactored import OOP as GUI 9 | 10 | class GuiUnitTests(unittest.TestCase): 11 | 12 | def test_TitleIsEnglish(self): 13 | i18n = I18N('en') 14 | self.assertEqual(i18n.title, 15 | "Python Graphical User Interface") 16 | 17 | def test_TitleIsGerman(self): 18 | # i18n = I18N('en') # <= Bug in Unit Test 19 | i18n = I18N('de') 20 | self.assertEqual(i18n.title, 21 | 'Python Grafische Benutzeroberfl' 22 | + "\u00E4" + 'che') 23 | 24 | class WidgetsTestsEnglish(unittest.TestCase): 25 | 26 | def setUp(self): 27 | self.gui = GUI('en') 28 | 29 | def tearDown(self): 30 | self.gui = None 31 | 32 | def test_WidgetLabels(self): 33 | self.assertEqual(self.gui.i18n.file, "File") 34 | self.assertEqual(self.gui.i18n.mgrFiles, ' Manage Files ') 35 | self.assertEqual(self.gui.i18n.browseTo, 36 | "Browse to File...") 37 | 38 | #========================== 39 | if __name__ == '__main__': 40 | unittest.main() 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /Chapter08/Ch08_Code/UnitTestsFail.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard 4 | ''' 5 | 6 | import unittest 7 | from Ch08_Code.LanguageResources import I18N 8 | from Ch08_Code.GUI_Refactored import OOP as GUI 9 | 10 | class GuiUnitTests(unittest.TestCase): 11 | 12 | def test_TitleIsEnglish(self): 13 | i18n = I18N('en') 14 | self.assertEqual(i18n.title, 15 | "Python Graphical User Interface") 16 | 17 | def test_TitleIsGerman(self): 18 | i18n = I18N('en') # <= Bug in Unit Test 19 | i18n = I18N('de') 20 | self.assertEqual(i18n.title, 21 | 'Python Grafische Benutzeroberfl' 22 | + "\u00E4" + 'che') 23 | 24 | 25 | #========================================================== 26 | if __name__ == '__main__': 27 | unittest.main() 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /Chapter08/Ch08_Code/UnitTestsMinimum.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | 6 | import unittest 7 | 8 | class GuiUnitTests(unittest.TestCase): 9 | pass 10 | 11 | if __name__ == '__main__': 12 | unittest.main() 13 | -------------------------------------------------------------------------------- /Chapter08/Ch08_Code/UnitTests_One.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard 4 | ''' 5 | 6 | import unittest 7 | from Ch08_Code.LanguageResources import I18N 8 | 9 | class GuiUnitTests(unittest.TestCase): 10 | 11 | def test_TitleIsEnglish(self): 12 | i18n = I18N('en') 13 | self.assertEqual(i18n.title, 14 | "Python Graphical User Interface") 15 | 16 | #========================== 17 | if __name__ == '__main__': 18 | unittest.main() 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /Chapter08/Ch08_Code/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Python-GUI-Programming-Cookbook-Second-Edition/1ca9866be88b4191a5a951cbc4ead7aad903f226/Chapter08/Ch08_Code/__init__.py -------------------------------------------------------------------------------- /Chapter08/Ch08_Code/logs/GUI_Refactored.log: -------------------------------------------------------------------------------- 1 | 2017-04-28 13:55:52 *** Starting Test *** 2 | -------------------------------------------------------------------------------- /Chapter08/Ch08_Code/pyc.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Python-GUI-Programming-Cookbook-Second-Edition/1ca9866be88b4191a5a951cbc4ead7aad903f226/Chapter08/Ch08_Code/pyc.ico -------------------------------------------------------------------------------- /Chapter09/Ch09_Code/Communicate.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | 6 | #================================================================== 7 | import tkinter as tk 8 | from tkinter import ttk 9 | from threading import Thread 10 | 11 | win = tk.Tk() 12 | win.title("Python GUI") 13 | ttk.Label(win, text="Enter a name:").grid(column=0, row=0) 14 | 15 | name = tk.StringVar() 16 | nameEntered = ttk.Entry(win, width=12, textvariable=name) 17 | nameEntered.grid(column=0, row=1) 18 | nameEntered.focus() 19 | 20 | ttk.Label(win, text="Choose a number:").grid(column=1, row=0) 21 | number = tk.StringVar() 22 | numberChosen = ttk.Combobox(win, width=12, textvariable=number) 23 | numberChosen['values'] = (1, 2, 4, 42, 100) 24 | numberChosen.grid(column=1, row=1) 25 | numberChosen.current(0) 26 | 27 | text = tk.Text(win, height=10, width=40, borderwidth=2, wrap='word') 28 | text.grid(column=0, sticky='WE', columnspan=3) 29 | 30 | #================================================================== 31 | from multiprocessing import Queue 32 | # from queue import Queue 33 | sharedQueue = Queue() 34 | dataInQueue = False 35 | 36 | def putDataIntoQueue(data): 37 | global dataInQueue 38 | dataInQueue = True 39 | sharedQueue.put(data) 40 | 41 | def readDataFromQueue(): 42 | global dataInQueue 43 | dataInQueue = False 44 | return sharedQueue.get() 45 | 46 | #================================================================== 47 | import wx 48 | class GUI(wx.Panel): 49 | def __init__(self, parent): 50 | wx.Panel.__init__(self, parent) 51 | parent.CreateStatusBar() 52 | menu= wx.Menu() 53 | menu.Append(wx.ID_ABOUT, "About", "wxPython GUI") 54 | menuBar = wx.MenuBar() 55 | menuBar.Append(menu, "File") 56 | parent.SetMenuBar(menuBar) 57 | button = wx.Button(self, label="Print", pos=(0,60)) 58 | self.Bind(wx.EVT_BUTTON, self.writeToSharedQueue, button) 59 | self.textBox = wx.TextCtrl(self, size=(280,50), style=wx.TE_MULTILINE) 60 | 61 | #----------------------------------------------------------------- 62 | def writeToSharedQueue(self, event): 63 | self.textBox.AppendText( 64 | "The Print Button has been clicked!\n") 65 | putDataIntoQueue('Hi from wxPython via Shared Queue.\n') 66 | if dataInQueue: 67 | data = readDataFromQueue() 68 | self.textBox.AppendText(data) 69 | 70 | text.insert('0.0', data) # insert data into tkinter GUI 71 | 72 | #================================================================== 73 | def wxPythonApp(): 74 | app = wx.App() 75 | frame = wx.Frame( 76 | None, title="Python GUI using wxPython", size=(300,180)) 77 | GUI(frame) 78 | frame.Show() 79 | runT = Thread(target=app.MainLoop) 80 | runT.setDaemon(True) 81 | runT.start() 82 | print(runT) 83 | print('createThread():', runT.isAlive()) 84 | 85 | #================================================================== 86 | action = ttk.Button(win, text="Call wxPython GUI", command=wxPythonApp) 87 | action.grid(column=2, row=1) 88 | 89 | #====================== 90 | # Start GUI 91 | #====================== 92 | win.mainloop() -------------------------------------------------------------------------------- /Chapter09/Ch09_Code/Control_Frameworks.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | 6 | #================================================================== 7 | import tkinter as tk 8 | from tkinter import ttk 9 | from tkinter import scrolledtext 10 | from threading import Thread 11 | 12 | win = tk.Tk() 13 | 14 | win.title("Python GUI") 15 | aLabel = ttk.Label(win, text="A Label") 16 | aLabel.grid(column=0, row=0) 17 | ttk.Label(win, text="Enter a name:").grid(column=0, row=0) 18 | name = tk.StringVar() 19 | nameEntered = ttk.Entry(win, width=12, textvariable=name) 20 | nameEntered.grid(column=0, row=1) 21 | ttk.Label(win, text="Choose a number:").grid(column=1, row=0) 22 | number = tk.StringVar() 23 | numberChosen = ttk.Combobox(win, width=12, textvariable=number) 24 | numberChosen['values'] = (1, 2, 4, 42, 100) 25 | numberChosen.grid(column=1, row=1) 26 | numberChosen.current(0) 27 | scrolW = 30 28 | scrolH = 3 29 | scr = scrolledtext.ScrolledText(win, width=scrolW, height=scrolH, wrap=tk.WORD) 30 | scr.grid(column=0, sticky='WE', columnspan=3) 31 | nameEntered.focus() 32 | 33 | #================================================================== 34 | ## working 35 | def wxPythonApp(): 36 | import wx 37 | app = wx.App() 38 | frame = wx.Frame(None, -1, "wxPython GUI", size=(200,150)) 39 | frame.SetBackgroundColour('white') 40 | frame.CreateStatusBar() 41 | menu= wx.Menu() 42 | menu.Append(wx.ID_ABOUT, "About", "wxPython GUI") 43 | menuBar = wx.MenuBar() 44 | menuBar.Append(menu,"File") 45 | frame.SetMenuBar(menuBar) 46 | frame.Show() 47 | 48 | runT = Thread(target=app.MainLoop) 49 | runT.setDaemon(True) 50 | runT.start() 51 | print(runT) 52 | print('createThread():', runT.isAlive()) 53 | 54 | action = ttk.Button(win, text="Call wxPython GUI", command=wxPythonApp) 55 | action.grid(column=2, row=1) 56 | #================================================================== 57 | 58 | 59 | ## NOT working - CRASHES Python ----------------------------------- 60 | # def wxPythonApp(): 61 | # import wx 62 | # app = wx.App() 63 | # frame = wx.Frame(None, -1, "wxPython GUI", size=(200,150)) 64 | # frame.SetBackgroundColour('white') 65 | # frame.CreateStatusBar() 66 | # menu= wx.Menu() 67 | # menu.Append(wx.ID_ABOUT, "About", "wxPython GUI") 68 | # menuBar = wx.MenuBar() 69 | # menuBar.Append(menu,"File") 70 | # frame.SetMenuBar(menuBar) 71 | # frame.Show() 72 | # app.MainLoop() 73 | # 74 | # def tryRunInThread(): 75 | # runT = Thread(target=wxPythonApp) 76 | # runT.setDaemon(True) 77 | # runT.start() 78 | # print(runT) 79 | # print('createThread():', runT.isAlive()) 80 | # 81 | # action = ttk.Button(win, text="Call wxPython GUI", command=tryRunInThread) 82 | # action.grid(column=2, row=1) 83 | ##----------------------------------------------------------------- 84 | 85 | #====================== 86 | # Start GUI 87 | #====================== 88 | win.mainloop() -------------------------------------------------------------------------------- /Chapter09/Ch09_Code/Control_Frameworks_NOT_working.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | 6 | #================================================================== 7 | import tkinter as tk 8 | from tkinter import ttk 9 | from tkinter import scrolledtext 10 | from threading import Thread 11 | 12 | win = tk.Tk() 13 | 14 | win.title("Python GUI") 15 | aLabel = ttk.Label(win, text="A Label") 16 | aLabel.grid(column=0, row=0) 17 | ttk.Label(win, text="Enter a name:").grid(column=0, row=0) 18 | name = tk.StringVar() 19 | nameEntered = ttk.Entry(win, width=12, textvariable=name) 20 | nameEntered.grid(column=0, row=1) 21 | ttk.Label(win, text="Choose a number:").grid(column=1, row=0) 22 | number = tk.StringVar() 23 | numberChosen = ttk.Combobox(win, width=12, textvariable=number) 24 | numberChosen['values'] = (1, 2, 4, 42, 100) 25 | numberChosen.grid(column=1, row=1) 26 | numberChosen.current(0) 27 | scrolW = 30 28 | scrolH = 3 29 | scr = scrolledtext.ScrolledText(win, width=scrolW, height=scrolH, wrap=tk.WORD) 30 | scr.grid(column=0, sticky='WE', columnspan=3) 31 | nameEntered.focus() 32 | 33 | #================================================================== 34 | # NOT working - CRASHES Python ----------------------------------- 35 | def wxPythonApp(): 36 | import wx 37 | app = wx.App() 38 | frame = wx.Frame(None, -1, "wxPython GUI", size=(200,150)) 39 | frame.SetBackgroundColour('white') 40 | frame.CreateStatusBar() 41 | menu= wx.Menu() 42 | menu.Append(wx.ID_ABOUT, "About", "wxPython GUI") 43 | menuBar = wx.MenuBar() 44 | menuBar.Append(menu,"File") 45 | frame.SetMenuBar(menuBar) 46 | frame.Show() 47 | app.MainLoop() 48 | 49 | def tryRunInThread(): 50 | runT = Thread(target=wxPythonApp) 51 | runT.setDaemon(True) 52 | runT.start() 53 | print(runT) 54 | print('createThread():', runT.isAlive()) 55 | 56 | action = ttk.Button(win, text="Call wxPython GUI", command=tryRunInThread) 57 | action.grid(column=2, row=1) 58 | #----------------------------------------------------------------- 59 | 60 | #====================== 61 | # Start GUI 62 | #====================== 63 | win.mainloop() -------------------------------------------------------------------------------- /Chapter09/Ch09_Code/Embed_tkinter.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | 6 | #================================================================== 7 | def tkinterApp(): 8 | import tkinter as tk 9 | from tkinter import ttk 10 | win = tk.Tk() 11 | win.title("Python GUI") 12 | aLabel = ttk.Label(win, text="A Label") 13 | aLabel.grid(column=0, row=0) 14 | ttk.Label(win, text="Enter a name:").grid(column=0, row=0) 15 | name = tk.StringVar() 16 | nameEntered = ttk.Entry(win, width=12, textvariable=name) 17 | nameEntered.grid(column=0, row=1) 18 | nameEntered.focus() 19 | 20 | def buttonCallback(): 21 | action.configure(text='Hello ' + name.get()) 22 | action = ttk.Button(win, text="Print", command=buttonCallback) 23 | action.grid(column=2, row=1) 24 | win.mainloop() 25 | 26 | #================================================================== 27 | import wx 28 | app = wx.App() 29 | frame = wx.Frame(None, -1, "wxPython GUI", size=(270,180)) 30 | frame.SetBackgroundColour('white') 31 | frame.CreateStatusBar() 32 | menu= wx.Menu() 33 | menu.Append(wx.ID_ABOUT, "About", "wxPython GUI") 34 | menuBar = wx.MenuBar() 35 | menuBar.Append(menu,"File") 36 | frame.SetMenuBar(menuBar) 37 | textBox = wx.TextCtrl(frame, size=(250, 50), style=wx.TE_MULTILINE) 38 | 39 | def writeToSharedQueue(event): 40 | tkinterApp() 41 | 42 | button = wx.Button(frame, label="Call tkinter GUI", pos=(0,60)) 43 | frame.Bind(wx.EVT_BUTTON, writeToSharedQueue, button) 44 | frame.Show() 45 | 46 | #====================== 47 | # Start wxPython GUI 48 | #====================== 49 | app.MainLoop() -------------------------------------------------------------------------------- /Chapter09/Ch09_Code/Embed_wxPython.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | 6 | #================================================================== 7 | import tkinter as tk 8 | from tkinter import ttk 9 | from tkinter import scrolledtext 10 | 11 | win = tk.Tk() 12 | 13 | win.title("Python GUI") 14 | aLabel = ttk.Label(win, text="A Label") 15 | aLabel.grid(column=0, row=0) 16 | ttk.Label(win, text="Enter a name:").grid(column=0, row=0) 17 | name = tk.StringVar() 18 | nameEntered = ttk.Entry(win, width=12, textvariable=name) 19 | nameEntered.grid(column=0, row=1) 20 | ttk.Label(win, text="Choose a number:").grid(column=1, row=0) 21 | number = tk.StringVar() 22 | numberChosen = ttk.Combobox(win, width=12, textvariable=number) 23 | numberChosen['values'] = (1, 2, 4, 42, 100) 24 | numberChosen.grid(column=1, row=1) 25 | numberChosen.current(0) 26 | scrolW = 30 27 | scrolH = 3 28 | scr = scrolledtext.ScrolledText(win, width=scrolW, height=scrolH, wrap=tk.WORD) 29 | scr.grid(column=0, sticky='WE', columnspan=3) 30 | nameEntered.focus() 31 | 32 | #================================================================== 33 | def wxPythonApp(): 34 | import wx 35 | app = wx.App() 36 | frame = wx.Frame(None, -1, "wxPython GUI", size=(200,150)) 37 | frame.SetBackgroundColour('white') 38 | frame.CreateStatusBar() 39 | menu= wx.Menu() 40 | menu.Append(wx.ID_ABOUT, "About", "wxPython GUI") 41 | menuBar = wx.MenuBar() 42 | menuBar.Append(menu, "File") 43 | frame.SetMenuBar(menuBar) 44 | frame.Show() 45 | app.MainLoop() 46 | 47 | 48 | action = ttk.Button(win, text="Call wxPython GUI", command=wxPythonApp) 49 | action.grid(column=2, row=1) 50 | 51 | #====================== 52 | # Start GUI 53 | #====================== 54 | win.mainloop() -------------------------------------------------------------------------------- /Chapter09/Ch09_Code/Hello_wxPython.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | 6 | import wx 7 | app = wx.App() 8 | frame = wx.Frame(None, -1, "Hello World") 9 | frame.Show() 10 | app.MainLoop() 11 | -------------------------------------------------------------------------------- /Chapter09/Ch09_Code/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Python-GUI-Programming-Cookbook-Second-Edition/1ca9866be88b4191a5a951cbc4ead7aad903f226/Chapter09/Ch09_Code/__init__.py -------------------------------------------------------------------------------- /Chapter09/Ch09_Code/wxPython_frame_GUI.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | 6 | # Import wxPython GUI toolkit 7 | import wx 8 | 9 | # Subclass wxPython frame 10 | class GUI(wx.Frame): 11 | def __init__(self, parent, title, size=(200,100)): 12 | # Initialize super class 13 | wx.Frame.__init__(self, parent, title=title, size=size) 14 | 15 | # Change the frame color 16 | self.SetBackgroundColour('white') 17 | 18 | # Create Status Bar 19 | self.CreateStatusBar() 20 | 21 | # Create the Menu 22 | menu= wx.Menu() 23 | 24 | # Add Menu Items to the Menu 25 | menu.Append(wx.ID_ABOUT, "About", "wxPython GUI") 26 | menu.AppendSeparator() 27 | menu.Append(wx.ID_EXIT,"Exit"," Exit the GUI") 28 | 29 | # Create the MenuBar 30 | menuBar = wx.MenuBar() 31 | # Give the Menu a Title 32 | menuBar.Append(menu,"File") 33 | 34 | # Connect the Menu to the frame 35 | self.SetMenuBar(menuBar) 36 | 37 | # Display the frame 38 | self.Show() 39 | 40 | # Create instance of wxPython application 41 | app = wx.App() 42 | 43 | # Call sub-classed wxPython GUI 44 | GUI(None, "Python GUI using wxPython", (300,150)) 45 | 46 | # Run the main GUI event loop 47 | app.MainLoop() 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /Chapter09/Ch09_Code/wxPython_panel_GUI.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | 6 | import wx # Import wxPython GUI toolkit 7 | class GUI(wx.Panel): # Subclass wxPython Panel 8 | def __init__(self, parent): 9 | 10 | # Initialize super class 11 | wx.Panel.__init__(self, parent) 12 | 13 | # Create Status Bar 14 | parent.CreateStatusBar() 15 | 16 | # Create the Menu 17 | menu= wx.Menu() 18 | 19 | # Add Menu Items to the Menu 20 | menu.Append(wx.ID_ABOUT, "About", "wxPython GUI") 21 | menu.AppendSeparator() 22 | menu.Append(wx.ID_EXIT, "Exit"," Exit the GUI") 23 | 24 | # Create the MenuBar 25 | menuBar = wx.MenuBar() 26 | 27 | # Give the Menu a Title 28 | menuBar.Append(menu, "File") 29 | 30 | # Connect the MenuBar to the frame 31 | parent.SetMenuBar(menuBar) 32 | 33 | # Create a Print Button 34 | button = wx.Button(self, label="Print", pos=(0,60)) 35 | 36 | # Connect Button to Click Event method 37 | self.Bind(wx.EVT_BUTTON, self.printButton, button) 38 | 39 | # Create a Text Control widget 40 | self.textBox = wx.TextCtrl(self, size=(280,50), style=wx.TE_MULTILINE) 41 | 42 | 43 | # callback event handler 44 | def printButton(self, event): 45 | # Click Event method 46 | self.textBox.AppendText("The Print Button has been clicked!") 47 | 48 | 49 | app = wx.App() # Create instance of wxPython application 50 | # Create frame 51 | frame = wx.Frame(None, title="Python GUI using wxPython", size=(300,180)) 52 | GUI(frame) # Pass frame into GUI 53 | frame.Show() # Display the frame 54 | app.MainLoop() # Run the main GUI event loop 55 | -------------------------------------------------------------------------------- /Chapter10/Ch10_Code/OpenGL_SuperBible_Animation.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | Example translated into Python from: 4 | "OpenGL SuperBible Fourth Edition" starting at page 62 5 | @author: Burkhard A. Meier 6 | ''' 7 | 8 | from OpenGL.GLUT import * 9 | from OpenGL.GL import * 10 | from OpenGL.GLU import * 11 | 12 | # initial position and size 13 | x = GLfloat(0.0).value 14 | y = GLfloat(0.0).value 15 | rect_size = GLfloat(25.0).value 16 | 17 | # number of pixels to move each step 18 | xstep = GLfloat(1.0).value 19 | ystep = GLfloat(1.0).value 20 | 21 | # initialize bouncing window 22 | windowWidth = GLfloat(133).value # 800/600 = 1.33 23 | windowHeight = GLfloat(100).value 24 | 25 | 26 | def RenderScene(): # display callback function 27 | glClear(GL_COLOR_BUFFER_BIT) # clear window with color defined in SetupRC 28 | # R G B # set drawing color to Red 29 | glColor3f(1.0, 0.0, 0.0) # functions expects 3 f(loats) 30 | glRectf(x, y, x + rect_size, y - rect_size) # draw a filled rectangle with above color 31 | 32 | glutSwapBuffers() # flush and swap double buffers 33 | 34 | 35 | def TimerFunction(value): 36 | global x, xstep, y, ystep 37 | 38 | # reverse direction left/right 39 | if ((x > windowWidth - rect_size) or (x < -windowWidth)): 40 | xstep = -xstep 41 | 42 | # reverse direction top/bottom 43 | if ((y > windowHeight) or (y < -windowHeight + rect_size)): 44 | ystep = -ystep 45 | 46 | # move the red square 47 | x += xstep 48 | y += ystep 49 | 50 | # check the bounds of the clipping area 51 | if (x > (windowWidth - rect_size + xstep)): 52 | x = windowWidth - rect_size - 1 53 | elif (x < -(windowWidth + xstep)): 54 | x = -windowWidth - 1 55 | 56 | if (y > (windowHeight + ystep)): 57 | y = windowHeight - 1 58 | elif (y < -(windowHeight - rect_size + ystep)): 59 | y = -windowHeight + rect_size - 1 60 | 61 | # redraw the scene 62 | glutPostRedisplay() 63 | glutTimerFunc(33, TimerFunction, 1) # recursive call 64 | 65 | 66 | def SetupRC(): # rendering context setup 67 | glClearColor(0.0, 0.0, 1.0, 1.0) # RGBA: R=0.0, G=0.0, B=1.0=white => becomes Blue 68 | 69 | 70 | def ChangeSize(w, h): 71 | if h == 0: h =1 # prevent divide by zero 72 | 73 | glViewport(0, 0, w, h) # set Viewport to Window dimensions 74 | 75 | glMatrixMode(GL_PROJECTION) # define the viewing volume 76 | glLoadIdentity() # reset coordinate system 77 | 78 | aspectRatio = GLfloat(w).value / GLfloat(h).value # establish clipping volume 79 | # GLfloat becomes ctypes.c_float 80 | # Use the value attribute before dividing 81 | if w <= h: 82 | windowWidth = 100 83 | windowHeight = 100 / aspectRatio 84 | glOrtho(-100.0, 100.0, -windowHeight, windowHeight, 1.0, -1.0) 85 | else: 86 | windowWidth = 100 * aspectRatio 87 | windowHeight = 100 88 | glOrtho(-windowWidth, windowWidth, -100.0, 100.0, 1.0, -1.0) 89 | 90 | glMatrixMode(GL_MODELVIEW) 91 | glLoadIdentity() 92 | 93 | 94 | def main(): 95 | glutInit() 96 | glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB) # Double buffer 97 | glutInitWindowSize(800, 600) # window size 98 | glutCreateWindow(b"Bouncing Red Square") # Python 3: bytes instead of string for Title 99 | glutDisplayFunc(RenderScene) 100 | glutReshapeFunc(ChangeSize) 101 | glutTimerFunc(33, TimerFunction, 1) 102 | 103 | SetupRC() 104 | 105 | glutMainLoop() 106 | 107 | #================= 108 | main() 109 | -------------------------------------------------------------------------------- /Chapter10/Ch10_Code/OpenGL_SuperBible_Simple.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | Example translated into Python from: 4 | "OpenGL SuperBible Fourth Edition" starting at page 48 5 | @author: Burkhard A. Meier 6 | ''' 7 | 8 | from OpenGL.GLUT import * 9 | from OpenGL.GL import * 10 | from OpenGL.GLU import * 11 | 12 | 13 | def RenderScene(): # display callback function 14 | glClear(GL_COLOR_BUFFER_BIT) # clear window with color defined in SetupRC 15 | glFlush() # flush/execute the OpenGL drawing command(s) 16 | 17 | def SetupRC(): # rendering context 18 | glClearColor(0.0, 0.0, 1.0, 1.0) # RGBA: R=0.0, G=0.0, B=1.0 => becomes Blue 19 | 20 | def main(): 21 | glutInit() 22 | glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA) # single buffer; RGBA color mode 23 | glutCreateWindow(b"Simple") # Python 3: bytes instead of string for Title 24 | glutDisplayFunc(RenderScene) 25 | SetupRC() 26 | 27 | glutMainLoop() 28 | 29 | #================= 30 | main() 31 | -------------------------------------------------------------------------------- /Chapter10/Ch10_Code/OpenGL_SuperBible_Simple_Rectangle.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | Example translated into Python from: 4 | "OpenGL SuperBible Fourth Edition" starting at page 54 5 | @author: Burkhard A. Meier 6 | ''' 7 | 8 | from OpenGL.GLUT import * 9 | from OpenGL.GL import * 10 | from OpenGL.GLU import * 11 | 12 | def RenderScene(): # display callback function 13 | glClear(GL_COLOR_BUFFER_BIT) # clear window with color defined in SetupRC 14 | # R G B # set drawing color to Red 15 | glColor3f(1.0, 0.0, 0.0) # function expects 3 f(loats) 16 | glRectf(-25.0, 25.0, 25.0, -25.0) # draw a filled rectangle with above color 17 | glFlush() # flush/execute the OpenGL drawing command(s) 18 | 19 | def SetupRC(): # rendering context setup 20 | glClearColor(0.0, 0.0, 1.0, 1.0) # RGBA: R=0.0, G=0.0, B=1.0=white => becomes Blue 21 | 22 | def ChangeSize(w, h): # callback when window size changes 23 | if h == 0: h =1 # prevent divide by zero 24 | glViewport(0, 0, w, h) # set Viewport to Window dimensions 25 | glMatrixMode(GL_PROJECTION) # define the viewing volume 26 | glLoadIdentity() # reset coordinate system 27 | aspectRatio = GLfloat(w).value / GLfloat(h).value # establish clipping volume 28 | # GLfloat becomes ctypes.c_float 29 | # Use the value attribute before dividing 30 | if w <= h: glOrtho(-100.0, 100.0, -100.0 / aspectRatio, 100.0 / aspectRatio, 1.0, -1.0) 31 | else: glOrtho(-100.0 * aspectRatio, 100.0 * aspectRatio, -100.0, 100.0, 1.0, -1.0) 32 | glMatrixMode(GL_MODELVIEW) 33 | glLoadIdentity() 34 | 35 | def main(): 36 | glutInit() 37 | glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA) # single buffer; RGBA color mode 38 | glutCreateWindow(b"GLRect") # Python 3: bytes instead of string for Title 39 | glutDisplayFunc(RenderScene) 40 | glutReshapeFunc(ChangeSize) 41 | SetupRC() 42 | glutMainLoop() 43 | #================= 44 | main() 45 | -------------------------------------------------------------------------------- /Chapter10/Ch10_Code/Resources/Galaxy.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Python-GUI-Programming-Cookbook-Second-Edition/1ca9866be88b4191a5a951cbc4ead7aad903f226/Chapter10/Ch10_Code/Resources/Galaxy.gif -------------------------------------------------------------------------------- /Chapter10/Ch10_Code/Resources/LightsInTheCity.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Python-GUI-Programming-Cookbook-Second-Edition/1ca9866be88b4191a5a951cbc4ead7aad903f226/Chapter10/Ch10_Code/Resources/LightsInTheCity.gif -------------------------------------------------------------------------------- /Chapter10/Ch10_Code/Resources/NothernLights.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Python-GUI-Programming-Cookbook-Second-Edition/1ca9866be88b4191a5a951cbc4ead7aad903f226/Chapter10/Ch10_Code/Resources/NothernLights.gif -------------------------------------------------------------------------------- /Chapter10/Ch10_Code/Resources/Schloss_Neuschwarnstein.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Python-GUI-Programming-Cookbook-Second-Edition/1ca9866be88b4191a5a951cbc4ead7aad903f226/Chapter10/Ch10_Code/Resources/Schloss_Neuschwarnstein.jpg -------------------------------------------------------------------------------- /Chapter10/Ch10_Code/Resources/Sparkle.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Python-GUI-Programming-Cookbook-Second-Edition/1ca9866be88b4191a5a951cbc4ead7aad903f226/Chapter10/Ch10_Code/Resources/Sparkle.gif -------------------------------------------------------------------------------- /Chapter10/Ch10_Code/Resources/Universe.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Python-GUI-Programming-Cookbook-Second-Edition/1ca9866be88b4191a5a951cbc4ead7aad903f226/Chapter10/Ch10_Code/Resources/Universe.jpg -------------------------------------------------------------------------------- /Chapter10/Ch10_Code/Resources/rivers expedition day.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Python-GUI-Programming-Cookbook-Second-Edition/1ca9866be88b4191a5a951cbc4ead7aad903f226/Chapter10/Ch10_Code/Resources/rivers expedition day.jpg -------------------------------------------------------------------------------- /Chapter10/Ch10_Code/SlideShow.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | 6 | from tkinter import Tk, PhotoImage, Label 7 | from itertools import cycle 8 | from os import listdir, path, chdir 9 | 10 | class SlideShow(Tk): 11 | # inherit GUI framework extending tkinter 12 | def __init__(self, msShowTimeBetweenSlides=1500): 13 | # initialize tkinter super class 14 | Tk.__init__(self) 15 | 16 | # time each slide will be shown 17 | self.showTime = msShowTimeBetweenSlides 18 | 19 | # look for images in current working directory where this module lives 20 | chapter_folder = path.realpath(path.dirname(__file__)) 21 | resources_folder = path.join(chapter_folder, 'Resources') 22 | listOfSlides = [slide for slide in listdir(resources_folder) if slide.endswith('gif')] 23 | 24 | # endlessly read in the slides so we can show them on the tkinter Label 25 | chdir(resources_folder) 26 | self.iterableCycle = cycle((PhotoImage(file=slide), slide) for slide in listOfSlides) 27 | 28 | # create tkinter Label widget which can also display images 29 | self.slidesLabel = Label(self) 30 | 31 | # create the Frame widget 32 | self.slidesLabel.pack() 33 | 34 | 35 | def slidesCallback(self): 36 | # get next slide from iterable cycle 37 | currentInstance, nameOfSlide = next(self.iterableCycle) 38 | 39 | # assign next slide to Label widget 40 | self.slidesLabel.config(image=currentInstance) 41 | 42 | # update Window title with current slide 43 | self.title(nameOfSlide) 44 | 45 | # recursively repeat the Show 46 | self.after(self.showTime, self.slidesCallback) 47 | 48 | 49 | #================================= 50 | # Start GUI 51 | #================================= 52 | win = SlideShow() 53 | win.after(0, win.slidesCallback()) 54 | win.mainloop() 55 | -------------------------------------------------------------------------------- /Chapter10/Ch10_Code/SlideShow_Pillow.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | 6 | from tkinter import Tk, Label 7 | from itertools import cycle 8 | from os import listdir, path, chdir 9 | 10 | # using Pillow instead of PIL (2.7) for Python 3.6 11 | # Installation is: >pip install Pillow 12 | from PIL import ImageTk 13 | 14 | 15 | class SlideShow(Tk): 16 | # inherit GUI framework extending tkinter 17 | def __init__(self, msShowTimeBetweenSlides=1500): 18 | # initialize tkinter super class 19 | Tk.__init__(self) 20 | 21 | # time each slide will be shown 22 | self.showTime = msShowTimeBetweenSlides 23 | 24 | # look for images in current working directory where this module lives 25 | chapter_folder = path.realpath(path.dirname(__file__)) 26 | resources_folder = path.join(chapter_folder, 'Resources') 27 | listOfSlides = [slide for slide in listdir(resources_folder) if slide.endswith('gif') or slide.endswith('jpg')] 28 | 29 | # endlessly read in the slides so we can show them on the tkinter Label 30 | chdir(resources_folder) 31 | self.iterableCycle = cycle((ImageTk.PhotoImage(file=slide), slide) for slide in listOfSlides) 32 | 33 | # create tkinter Label widget which can also display images 34 | self.slidesLabel = Label(self) 35 | 36 | # create the Frame widget 37 | self.slidesLabel.pack() 38 | 39 | 40 | def slidesCallback(self): 41 | # get next slide from iterable cycle 42 | currentInstance, nameOfSlide = next(self.iterableCycle) 43 | 44 | # assign next slide to Label widget 45 | self.slidesLabel.config(image=currentInstance) 46 | 47 | # update Window title with current slide 48 | self.title(nameOfSlide) 49 | 50 | # recursively repeat the Show 51 | self.after(self.showTime, self.slidesCallback) 52 | 53 | 54 | #================================= 55 | # Start GUI 56 | #================================= 57 | win = SlideShow() 58 | win.after(0, win.slidesCallback()) 59 | win.mainloop() 60 | -------------------------------------------------------------------------------- /Chapter10/Ch10_Code/SlideShow_try_jpg.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | 6 | from tkinter import Tk, PhotoImage, Label 7 | from itertools import cycle 8 | from os import listdir, path, chdir 9 | 10 | class SlideShow(Tk): 11 | # inherit GUI framework extending tkinter 12 | def __init__(self, msShowTimeBetweenSlides=1500): 13 | # initialize tkinter super class 14 | Tk.__init__(self) 15 | 16 | # time each slide will be shown 17 | self.showTime = msShowTimeBetweenSlides 18 | 19 | # look for images in current working directory where this module lives 20 | # try: .jpeg 21 | chapter_folder = path.realpath(path.dirname(__file__)) 22 | resources_folder = path.join(chapter_folder, 'Resources') 23 | listOfSlides = [slide for slide in listdir(resources_folder) if slide.endswith('gif') or slide.endswith('jpg')] 24 | 25 | # endlessly read in the slides so we can show them on the tkinter Label 26 | chdir(resources_folder) 27 | self.iterableCycle = cycle((PhotoImage(file=slide), slide) for slide in listOfSlides) 28 | 29 | # create tkinter Label widget which can also display images 30 | self.slidesLabel = Label(self) 31 | 32 | # create the Frame widget 33 | self.slidesLabel.pack() 34 | 35 | 36 | def slidesCallback(self): 37 | # get next slide from iterable cycle 38 | currentInstance, nameOfSlide = next(self.iterableCycle) 39 | 40 | # assign next slide to Label widget 41 | self.slidesLabel.config(image=currentInstance) 42 | 43 | # update Window title with current slide 44 | self.title(nameOfSlide) 45 | 46 | # recursively repeat the Show 47 | self.after(self.showTime, self.slidesCallback) 48 | 49 | 50 | #================================= 51 | # Start GUI 52 | #================================= 53 | win = SlideShow() 54 | win.after(0, win.slidesCallback()) 55 | win.mainloop() 56 | -------------------------------------------------------------------------------- /Chapter10/Ch10_Code/Tile.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Python-GUI-Programming-Cookbook-Second-Edition/1ca9866be88b4191a5a951cbc4ead7aad903f226/Chapter10/Ch10_Code/Tile.bmp -------------------------------------------------------------------------------- /Chapter10/Ch10_Code/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Python-GUI-Programming-Cookbook-Second-Edition/1ca9866be88b4191a5a951cbc4ead7aad903f226/Chapter10/Ch10_Code/__init__.py -------------------------------------------------------------------------------- /Chapter10/Ch10_Code/import_OpenGL.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | 6 | 7 | import wx 8 | from wx import glcanvas 9 | from OpenGL.GL import * 10 | from OpenGL.GLUT import * 11 | 12 | -------------------------------------------------------------------------------- /Chapter10/Ch10_Code/pyglet_GUI.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | 6 | import pyglet 7 | from pyglet.gl import * 8 | from pyglet.window import key 9 | from OpenGL.GLUT import * 10 | 11 | WINDOW = 400 12 | INCREMENT = 5 13 | 14 | class Window(pyglet.window.Window): 15 | 16 | # Cube 3D start rotation 17 | xRotation = yRotation = 30 18 | 19 | def __init__(self, width, height, title=''): 20 | super(Window, self).__init__(width, height, title) 21 | glClearColor(0, 0, 0, 1) 22 | glEnable(GL_DEPTH_TEST) 23 | 24 | def on_draw(self): 25 | # Clear the current GL Window 26 | self.clear() 27 | 28 | # Push Matrix onto stack 29 | glPushMatrix() 30 | 31 | glRotatef(self.xRotation, 1, 0, 0) 32 | glRotatef(self.yRotation, 0, 1, 0) 33 | 34 | # Draw the six sides of the cube 35 | glBegin(GL_QUADS) 36 | 37 | # White 38 | glColor3ub(255, 255, 255) 39 | glVertex3f(50, 50, 50) 40 | 41 | # Yellow 42 | glColor3ub(255, 255, 0) 43 | glVertex3f(50, -50, 50) 44 | 45 | # Red 46 | glColor3ub(255, 0, 0) 47 | glVertex3f(-50, -50, 50) 48 | 49 | # Magenta 50 | glColor3ub(255, 0, 255) 51 | glVertex3f(-50, 50, 50) 52 | 53 | # Cyan 54 | glColor3f(0, 1, 1) 55 | glVertex3f(50, 50, -50) 56 | 57 | # Green 58 | glColor3f(0, 1, 0) 59 | glVertex3f(50, -50, -50) 60 | 61 | # Black 62 | glColor3f(0, 0, 0) 63 | glVertex3f(-50, -50, -50) 64 | 65 | # Blue 66 | glColor3f(0, 0, 1) 67 | glVertex3f(-50, 50, -50) 68 | 69 | # Cyan 70 | glColor3f(0, 1, 1) 71 | glVertex3f(50, 50, -50) 72 | 73 | # White 74 | glColor3f(1, 1, 1) 75 | glVertex3f(50, 50, 50) 76 | 77 | # Magenta 78 | glColor3f(1, 0, 1) 79 | glVertex3f(-50, 50, 50) 80 | 81 | # Blue 82 | glColor3f(0, 0, 1) 83 | glVertex3f(-50, 50, -50) 84 | 85 | # Green 86 | glColor3f(0, 1, 0) 87 | glVertex3f(50, -50, -50) 88 | 89 | # Yellow 90 | glColor3f(1, 1, 0) 91 | glVertex3f(50, -50, 50) 92 | 93 | # Red 94 | glColor3f(1, 0, 0) 95 | glVertex3f(-50, -50, 50) 96 | 97 | # Black 98 | glColor3f(0, 0, 0) 99 | glVertex3f(-50, -50, -50) 100 | 101 | # White 102 | glColor3f(1, 1, 1) 103 | glVertex3f(50, 50, 50) 104 | 105 | # Cyan 106 | glColor3f(0, 1, 1) 107 | glVertex3f(50, 50, -50) 108 | 109 | # Green 110 | glColor3f(0, 1, 0) 111 | glVertex3f(50, -50, -50) 112 | 113 | # Yellow 114 | glColor3f(1, 1, 0) 115 | glVertex3f(50, -50, 50) 116 | 117 | # Magenta 118 | glColor3f(1, 0, 1) 119 | glVertex3f(-50, 50, 50) 120 | 121 | # Blue 122 | glColor3f(0, 0, 1) 123 | glVertex3f(-50, 50, -50) 124 | 125 | # Black 126 | glColor3f(0, 0, 0) 127 | glVertex3f(-50, -50, -50) 128 | 129 | # Red 130 | glColor3f(1, 0, 0) 131 | glVertex3f(-50, -50, 50) 132 | 133 | glEnd() 134 | 135 | # Pop Matrix off stack 136 | glPopMatrix() 137 | 138 | 139 | def on_resize(self, width, height): 140 | # set the Viewport 141 | glViewport(0, 0, width, height) 142 | 143 | # using Projection mode 144 | glMatrixMode(GL_PROJECTION) 145 | glLoadIdentity() 146 | 147 | aspectRatio = width / height 148 | gluPerspective(35, aspectRatio, 1, 1000) 149 | 150 | glMatrixMode(GL_MODELVIEW) 151 | glLoadIdentity() 152 | glTranslatef(0, 0, -400) 153 | 154 | 155 | def on_text_motion(self, motion): 156 | if motion == key.UP: 157 | self.xRotation -= INCREMENT 158 | elif motion == key.DOWN: 159 | self.xRotation += INCREMENT 160 | elif motion == key.LEFT: 161 | self.yRotation -= INCREMENT 162 | elif motion == key.RIGHT: 163 | self.yRotation += INCREMENT 164 | 165 | 166 | if __name__ == '__main__': 167 | Window(WINDOW, WINDOW, 'Pyglet Colored Cube') 168 | pyglet.app.run() 169 | -------------------------------------------------------------------------------- /Chapter10/Ch10_Code/pyglet_GUI_Simple.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard A. Meier 4 | ''' 5 | 6 | import pyglet 7 | 8 | window = pyglet.window.Window() 9 | label = pyglet.text.Label('PyGLet GUI', 10 | font_size=42, 11 | x=window.width // 2, y=window.height // 2, 12 | anchor_x='center', anchor_y='center') 13 | 14 | @window.event 15 | def on_draw(): 16 | window.clear() 17 | label.draw() 18 | 19 | pyglet.app.run() 20 | -------------------------------------------------------------------------------- /Chapter11/Ch11_Code/Folder1/Folder2/Folder3/MessageBox.py: -------------------------------------------------------------------------------- 1 | from tkinter import messagebox 2 | 3 | def clickMe(): 4 | messagebox.showinfo('Imported Message Box', 'Hi from Level 3') 5 | 6 | 7 | -------------------------------------------------------------------------------- /Chapter11/Ch11_Code/GUI_DesignPattern.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard 4 | ''' 5 | 6 | import tkinter as tk 7 | from tkinter import ttk 8 | from tkinter import scrolledtext 9 | from tkinter import Menu 10 | 11 | class ButtonFactory(): 12 | def createButton(self, type_): 13 | return buttonTypes[type_]() 14 | 15 | class ButtonBase(): 16 | relief ='flat' 17 | foreground ='white' 18 | def getButtonConfig(self): 19 | return self.relief, self.foreground 20 | 21 | class ButtonRidge(ButtonBase): 22 | relief ='ridge' 23 | foreground ='red' 24 | 25 | class ButtonSunken(ButtonBase): 26 | relief ='sunken' 27 | foreground ='blue' 28 | 29 | class ButtonGroove(ButtonBase): 30 | relief ='groove' 31 | foreground ='green' 32 | 33 | buttonTypes = [ButtonRidge, ButtonSunken, ButtonGroove] 34 | 35 | class OOP(): 36 | def __init__(self): 37 | self.win = tk.Tk() 38 | self.win.title("Python GUI") 39 | self.createWidgets() 40 | 41 | def createWidgets(self): 42 | tabControl = ttk.Notebook(self.win) 43 | tab1 = ttk.Frame(tabControl) 44 | tabControl.add(tab1, text='Tab 1') 45 | tabControl.pack(expand=1, fill="both") 46 | self.monty = ttk.LabelFrame(tab1, text=' Monty Python ') 47 | self.monty.grid(column=0, row=0, padx=8, pady=4) 48 | 49 | scr = scrolledtext.ScrolledText(self.monty, width=30, height=3, wrap=tk.WORD) 50 | scr.grid(column=0, row=3, sticky='WE', columnspan=3) 51 | 52 | menuBar = Menu(tab1) 53 | self.win.config(menu=menuBar) 54 | fileMenu = Menu(menuBar, tearoff=0) 55 | menuBar.add_cascade(label="File", menu=fileMenu) 56 | helpMenu = Menu(menuBar, tearoff=0) 57 | menuBar.add_cascade(label="Help", menu=helpMenu) 58 | 59 | self.createButtons() 60 | 61 | 62 | def createButtons(self): 63 | 64 | factory = ButtonFactory() 65 | 66 | # Button 1 67 | rel = factory.createButton(0).getButtonConfig()[0] 68 | fg = factory.createButton(0).getButtonConfig()[1] 69 | action = tk.Button(self.monty, text="Button "+str(0+1), relief=rel, foreground=fg) 70 | action.grid(column=0, row=1) 71 | 72 | # Button 2 73 | rel = factory.createButton(1).getButtonConfig()[0] 74 | fg = factory.createButton(1).getButtonConfig()[1] 75 | action = tk.Button(self.monty, text="Button "+str(1+1), relief=rel, foreground=fg) 76 | action.grid(column=1, row=1) 77 | 78 | # Button 3 79 | rel = factory.createButton(2).getButtonConfig()[0] 80 | fg = factory.createButton(2).getButtonConfig()[1] 81 | action = tk.Button(self.monty, text="Button "+str(2+1), relief=rel, foreground=fg) 82 | action.grid(column=2, row=1) 83 | 84 | # # using a loop to do the above 85 | # for idx in range(len(buttonTypes)): 86 | # rel = factory.createButton(idx).getButtonConfig()[0] 87 | # fg = factory.createButton(idx).getButtonConfig()[1] 88 | # 89 | # action = tk.Button(self.monty, text="Button "+str(idx+1), relief=rel, foreground=fg) 90 | # action.grid(column=idx, row=1) 91 | 92 | #========================== 93 | oop = OOP() 94 | oop.win.mainloop() 95 | 96 | -------------------------------------------------------------------------------- /Chapter11/Ch11_Code/GUI_FallDown.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard 4 | ''' 5 | 6 | #====================== 7 | # imports 8 | #====================== 9 | import tkinter as tk 10 | from tkinter import ttk 11 | from tkinter import messagebox 12 | 13 | #----------------------------------------------- 14 | class ToolTip(object): 15 | def __init__(self, widget): 16 | self.widget = widget 17 | self.tipwindow = None 18 | self.id = None 19 | self.x = self.y = 0 20 | 21 | def showtip(self, text): 22 | "Display text in a ToolTip window" 23 | self.text = text 24 | if self.tipwindow or not self.text: return 25 | try: 26 | x, y, _cx, cy = self.widget.bbox("insert") 27 | x = x + self.widget.winfo_rootx() + 25 28 | y = y + cy + self.widget.winfo_rooty() +25 29 | self.tipwindow = tw = tk.Toplevel(self.widget) 30 | tw.wm_overrideredirect(1) 31 | tw.wm_geometry("+%d+%d" % (x, y)) 32 | label = tk.Label(tw, text=self.text, justify=tk.LEFT, 33 | background="#ffffe0", relief=tk.SOLID, borderwidth=1, 34 | font=("tahoma", "8", "normal")) 35 | label.pack(ipadx=1) 36 | except: pass 37 | 38 | def hidetip(self): 39 | tw = self.tipwindow 40 | self.tipwindow = None 41 | if tw: 42 | tw.destroy() 43 | 44 | #=================================================================== 45 | def createToolTip(widget, text): 46 | toolTip = ToolTip(widget) 47 | def enter(event): toolTip.showtip(text) 48 | def leave(event): toolTip.hidetip() 49 | widget.bind('', enter) 50 | widget.bind('', leave) 51 | 52 | 53 | #====================== 54 | # Create instance 55 | #====================== 56 | win = tk.Tk() 57 | 58 | #====================== 59 | # Add a title 60 | #====================== 61 | win.title("Python GUI") 62 | 63 | #========================= 64 | # Disable resizing the GUI 65 | #========================= 66 | win.resizable(0,0) 67 | 68 | #=============================================================================== 69 | # Adding a LabelFrame, Textbox (Entry) and Combobox 70 | #=============================================================================== 71 | lFrame = ttk.LabelFrame(win, text="Python GUI Programming Cookbook") 72 | lFrame.grid(column=0, row=0, sticky='WE', padx=10, pady=10) 73 | 74 | #=============================================================================== 75 | # Labels 76 | #=============================================================================== 77 | ttk.Label(lFrame, text="Enter a name:").grid(column=0, row=0) 78 | ttk.Label(lFrame, text="Choose a number:").grid(column=1, row=0, sticky=tk.W) 79 | 80 | #=============================================================================== 81 | # Buttons click command 82 | #=============================================================================== 83 | def clickMe(name, number): 84 | messagebox.showinfo('Information Message Box', 'Hello ' + name + \ 85 | ', your number is: ' + number) 86 | 87 | #=============================================================================== 88 | # Creating several controls in a loop 89 | #=============================================================================== 90 | names = ['name0', 'name1', 'name2'] 91 | nameEntries = ['nameEntry0', 'nameEntry1', 'nameEntry2'] 92 | 93 | numbers = ['number0', 'number1', 'number2'] 94 | numberEntries = ['numberEntry0', 'numberEntry1', 'numberEntry2'] 95 | 96 | buttons = [] 97 | 98 | for idx in range(3): 99 | names[idx] = tk.StringVar() 100 | nameEntries[idx] = ttk.Entry(lFrame, width=12, textvariable=names[idx]) 101 | nameEntries[idx].grid(column=0, row=idx+1) 102 | nameEntries[idx].delete(0, tk.END) 103 | nameEntries[idx].insert(0, '') 104 | 105 | numbers[idx] = tk.StringVar() 106 | numberEntries[idx] = ttk.Combobox(lFrame, width=14, textvariable=numbers[idx]) 107 | numberEntries[idx]['values'] = (1+idx, 2+idx, 4+idx, 42+idx, 100+idx) 108 | numberEntries[idx].grid(column=1, row=idx+1) 109 | numberEntries[idx].current(0) 110 | 111 | button = ttk.Button(lFrame, text="Click Me "+str(idx+1), command=lambda idx=idx: clickMe(names[idx].get(), numbers[idx].get())) 112 | button.grid(column=2, row=idx+1, sticky=tk.W) 113 | buttons.append(button) 114 | 115 | # Add Tooltips to more widgets 116 | createToolTip(nameEntries[idx], 'This is an Entry widget.') 117 | createToolTip(numberEntries[idx], 'This is a DropDown widget.') 118 | createToolTip(buttons[idx], 'This is a Button widget.') 119 | 120 | #====================== 121 | # Start GUI 122 | #====================== 123 | win.mainloop() -------------------------------------------------------------------------------- /Chapter11/Ch11_Code/GUI_NOT_Spaghetti.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard 4 | ''' 5 | 6 | #====================== 7 | # imports 8 | #====================== 9 | import tkinter as tk 10 | from tkinter import ttk 11 | from tkinter import scrolledtext 12 | 13 | #====================== 14 | # Create instance 15 | #====================== 16 | win = tk.Tk() 17 | 18 | #====================== 19 | # Add a title 20 | #====================== 21 | win.title("Python GUI") 22 | 23 | #========================= 24 | # Disable resizing the GUI 25 | #========================= 26 | win.resizable(0,0) 27 | 28 | #=============================================================================== 29 | # Adding a LabelFrame, Textbox (Entry) and Combobox 30 | #=============================================================================== 31 | lFrame = ttk.LabelFrame(win, text="Python GUI Programming Cookbook") 32 | lFrame.grid(column=0, row=0, sticky='WE', padx=10, pady=10) 33 | 34 | #=============================================================================== 35 | # Using a scrolled Text control 36 | #=============================================================================== 37 | outputFrame = ttk.LabelFrame(win, text=' Type into the scrolled text control: ') 38 | outputFrame.grid(column=0, row=2, sticky='E', padx=8) 39 | scrolW = 30 40 | scrolH = 6 41 | scr = scrolledtext.ScrolledText(outputFrame, width=scrolW, height=scrolH, wrap=tk.WORD) 42 | scr.grid(column=1, row=0, sticky='WE') 43 | 44 | #=============================================================================== 45 | # Creating a checkbutton 46 | #=============================================================================== 47 | chVarUn = tk.IntVar() 48 | check2 = tk.Checkbutton(lFrame, text="Enabled", variable=chVarUn) 49 | check2.deselect() 50 | check2.grid(column=1, row=4, sticky=tk.W, columnspan=3) 51 | 52 | #====================== 53 | # Start GUI 54 | #====================== 55 | win.mainloop() -------------------------------------------------------------------------------- /Chapter11/Ch11_Code/GUI_Not_OOP.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard 4 | ''' 5 | 6 | import tkinter as tk 7 | from tkinter import ttk 8 | from tkinter import scrolledtext 9 | from tkinter import Menu 10 | 11 | def createWidgets(): 12 | tabControl = ttk.Notebook(win) 13 | tab1 = ttk.Frame(tabControl) 14 | tabControl.add(tab1, text='Tab 1') 15 | tabControl.pack(expand=1, fill="both") 16 | monty = ttk.LabelFrame(tab1, text=' Mighty Python ') 17 | monty.grid(column=0, row=0, padx=8, pady=4) 18 | 19 | ttk.Label(monty, text="Enter a name:").grid(column=0, row=0, sticky='W') 20 | name = tk.StringVar() 21 | nameEntered = ttk.Entry(monty, width=12, textvariable=name) 22 | nameEntered.grid(column=0, row=1, sticky='W') 23 | 24 | action = ttk.Button(monty, text="Click Me!") 25 | action.grid(column=2, row=1) 26 | 27 | ttk.Label(monty, text="Choose a number:").grid(column=1, row=0) 28 | number = tk.StringVar() 29 | numberChosen = ttk.Combobox(monty, width=12, textvariable=number) 30 | numberChosen['values'] = (42) 31 | numberChosen.grid(column=1, row=1) 32 | numberChosen.current(0) 33 | 34 | scrolW = 30; scrolH = 3 35 | scr = scrolledtext.ScrolledText(monty, width=scrolW, height=scrolH, wrap=tk.WORD) 36 | scr.grid(column=0, row=3, sticky='WE', columnspan=3) 37 | 38 | menuBar = Menu(tab1) 39 | win.config(menu=menuBar) 40 | fileMenu = Menu(menuBar, tearoff=0) 41 | menuBar.add_cascade(label="File", menu=fileMenu) 42 | helpMenu = Menu(menuBar, tearoff=0) 43 | menuBar.add_cascade(label="Help", menu=helpMenu) 44 | 45 | nameEntered.focus() 46 | #====================== 47 | win = tk.Tk() 48 | win.title("Python GUI") 49 | createWidgets() 50 | win.mainloop() 51 | 52 | -------------------------------------------------------------------------------- /Chapter11/Ch11_Code/GUI_OOP.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard 4 | ''' 5 | 6 | import tkinter as tk 7 | from tkinter import ttk 8 | from tkinter import scrolledtext 9 | from tkinter import Menu 10 | 11 | class OOP(): 12 | def __init__(self): 13 | self.win = tk.Tk() 14 | self.win.title("Python GUI") 15 | self.createWidgets() 16 | 17 | def createWidgets(self): 18 | tabControl = ttk.Notebook(self.win) 19 | tab1 = ttk.Frame(tabControl) 20 | tabControl.add(tab1, text='Tab 1') 21 | tabControl.pack(expand=1, fill="both") 22 | self.monty = ttk.LabelFrame(tab1, text=' Mighty Python ') 23 | self.monty.grid(column=0, row=0, padx=8, pady=4) 24 | 25 | ttk.Label(self.monty, text="Enter a name:").grid(column=0, row=0, sticky='W') 26 | self.name = tk.StringVar() 27 | nameEntered = ttk.Entry(self.monty, width=12, textvariable=self.name) 28 | nameEntered.grid(column=0, row=1, sticky='W') 29 | 30 | self.action = ttk.Button(self.monty, text="Click Me!") 31 | self.action.grid(column=2, row=1) 32 | 33 | ttk.Label(self.monty, text="Choose a number:").grid(column=1, row=0) 34 | number = tk.StringVar() 35 | numberChosen = ttk.Combobox(self.monty, width=12, textvariable=number) 36 | numberChosen['values'] = (42) 37 | numberChosen.grid(column=1, row=1) 38 | numberChosen.current(0) 39 | 40 | scrolW = 30; scrolH = 3 41 | self.scr = scrolledtext.ScrolledText(self.monty, width=scrolW, height=scrolH, wrap=tk.WORD) 42 | self.scr.grid(column=0, row=3, sticky='WE', columnspan=3) 43 | 44 | menuBar = Menu(tab1) 45 | self.win.config(menu=menuBar) 46 | fileMenu = Menu(menuBar, tearoff=0) 47 | menuBar.add_cascade(label="File", menu=fileMenu) 48 | helpMenu = Menu(menuBar, tearoff=0) 49 | menuBar.add_cascade(label="Help", menu=helpMenu) 50 | 51 | nameEntered.focus() 52 | #========================== 53 | oop = OOP() 54 | oop.win.mainloop() 55 | 56 | -------------------------------------------------------------------------------- /Chapter11/Ch11_Code/GUI_Spaghetti.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard 4 | ''' 5 | 6 | # Spaghetti Code ############################# 7 | def PRINTME(me):print(me) 8 | import tkinter 9 | x=y=z=1 10 | PRINTME(z) 11 | from tkinter import * 12 | scrolW=30;scrolH=6 13 | win=tkinter.Tk() 14 | if x:chVarUn=tkinter.IntVar() 15 | from tkinter import ttk 16 | WE='WE' 17 | import tkinter.scrolledtext 18 | outputFrame=tkinter.ttk.LabelFrame(win,text=' Type into the scrolled text control: ') 19 | scr=tkinter.scrolledtext.ScrolledText(outputFrame,width=scrolW,height=scrolH,wrap=tkinter.WORD) 20 | e='E' 21 | scr.grid(column=1,row=1,sticky=WE) 22 | outputFrame.grid(column=0,row=2,sticky=e,padx=8) 23 | lFrame=None 24 | if y:chck2=tkinter.Checkbutton(lFrame,text="Enabled",variable=chVarUn) 25 | wE='WE' 26 | if y==x:PRINTME(x) 27 | lFrame=tkinter.ttk.LabelFrame(win,text="Spaghetti") 28 | chck2.grid(column=1,row=4,sticky=tkinter.W,columnspan=3) 29 | PRINTME(z) 30 | lFrame.grid(column=0,row=0,sticky=wE,padx=10,pady=10) 31 | chck2.select() 32 | try: win.mainloop() 33 | except:PRINTME(x) 34 | chck2.deselect() 35 | if y==x:PRINTME(x) 36 | # End Pasta ############################# 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /Chapter11/Ch11_Code/GUI__init.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard 4 | ''' 5 | 6 | 7 | #====================== 8 | # imports 9 | #====================== 10 | import tkinter as tk 11 | from tkinter import ttk 12 | 13 | #====================== 14 | # Create instance 15 | #====================== 16 | win = tk.Tk() 17 | 18 | #====================== 19 | # Add a title 20 | #====================== 21 | win.title("Python GUI") 22 | 23 | #=============================================================================== 24 | # Adding a LabelFrame and a Button 25 | #=============================================================================== 26 | lFrame = ttk.LabelFrame(win, text="Python GUI Programming Cookbook") 27 | lFrame.grid(column=0, row=0, sticky='WE', padx=10, pady=10) 28 | 29 | def clickMe(): 30 | from tkinter import messagebox 31 | messagebox.showinfo('Message Box', 'Hi from same Level.') 32 | 33 | button = ttk.Button(lFrame, text="Click Me ", command=clickMe) 34 | button.grid(column=1, row=0, sticky=tk.S) 35 | 36 | #====================== 37 | # Start GUI 38 | #====================== 39 | win.mainloop() -------------------------------------------------------------------------------- /Chapter11/Ch11_Code/GUI__init_import_folder.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard 4 | ''' 5 | 6 | #====================== 7 | # imports 8 | #====================== 9 | import tkinter as tk 10 | from tkinter import ttk 11 | from Ch11_Code.Folder1.Folder2.Folder3.MessageBox import clickMe 12 | 13 | #====================== 14 | # Create instance 15 | #====================== 16 | win = tk.Tk() 17 | 18 | #====================== 19 | # Add a title 20 | #====================== 21 | win.title("Python GUI") 22 | 23 | #=============================================================================== 24 | # Adding a LabelFrame and a Button 25 | #=============================================================================== 26 | lFrame = ttk.LabelFrame(win, text="Python GUI Programming Cookbook") 27 | lFrame.grid(column=0, row=0, sticky='WE', padx=10, pady=10) 28 | 29 | # def clickMe(): 30 | # from tkinter import messagebox 31 | # messagebox.showinfo('Message Box', 'Hi from same Level.') 32 | # 33 | button = ttk.Button(lFrame, text="Click Me ", command=clickMe) 34 | button.grid(column=1, row=0, sticky=tk.S) 35 | 36 | #====================== 37 | # Start GUI 38 | #====================== 39 | win.mainloop() -------------------------------------------------------------------------------- /Chapter11/Ch11_Code/GUI__init_import_folder_directly.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard 4 | ''' 5 | 6 | #====================== 7 | # imports 8 | #====================== 9 | import tkinter as tk 10 | from tkinter import ttk 11 | 12 | import __init__ #@UnresolvedImport #@UnusedImport 13 | from MessageBox import clickMe #@UnresolvedImport 14 | 15 | #====================== 16 | # Create instance 17 | #====================== 18 | win = tk.Tk() 19 | 20 | #====================== 21 | # Add a title 22 | #====================== 23 | win.title("Python GUI") 24 | 25 | #=============================================================================== 26 | # Adding a LabelFrame and a Button 27 | #=============================================================================== 28 | lFrame = ttk.LabelFrame(win, text="Python GUI Programming Cookbook") 29 | lFrame.grid(column=0, row=0, sticky='WE', padx=10, pady=10) 30 | 31 | # def clickMe(): 32 | # from tkinter import messagebox 33 | # messagebox.showinfo('Message Box', 'Hi from same Level.') 34 | # 35 | button = ttk.Button(lFrame, text="Click Me ", command=clickMe) 36 | button.grid(column=1, row=0, sticky=tk.S) 37 | 38 | #====================== 39 | # Start GUI 40 | #====================== 41 | win.mainloop() -------------------------------------------------------------------------------- /Chapter11/Ch11_Code/ToolTip.py: -------------------------------------------------------------------------------- 1 | ''' 2 | May 2017 3 | @author: Burkhard 4 | ''' 5 | ############################################################# 6 | # NOTE: This module is meant to be imported by other modules. 7 | ############################################################# 8 | #====================== 9 | # imports 10 | #====================== 11 | import tkinter as tk 12 | 13 | class ToolTip(object): 14 | def __init__(self, widget): 15 | self.widget = widget 16 | self.tipwindow = None 17 | self.id = None 18 | self.x = self.y = 0 19 | 20 | def showtip(self, text): 21 | "Display text in tooltip window" 22 | self.text = text 23 | if self.tipwindow or not self.text: 24 | return 25 | x, y, _cx, cy = self.widget.bbox("insert") 26 | x = x + self.widget.winfo_rootx() + 27 27 | y = y + cy + self.widget.winfo_rooty() +27 28 | self.tipwindow = tw = tk.Toplevel(self.widget) 29 | tw.wm_overrideredirect(1) 30 | tw.wm_geometry("+%d+%d" % (x, y)) 31 | 32 | label = tk.Label(tw, text=self.text, justify=tk.LEFT, 33 | background="#ffffe0", relief=tk.SOLID, borderwidth=1, 34 | font=("tahoma", "8", "normal")) 35 | label.pack(ipadx=1) 36 | 37 | def hidetip(self): 38 | tw = self.tipwindow 39 | self.tipwindow = None 40 | if tw: 41 | tw.destroy() 42 | 43 | #=================================================================== 44 | def createToolTip(widget, text): 45 | toolTip = ToolTip(widget) 46 | def enter(event): 47 | toolTip.showtip(text) 48 | def leave(event): 49 | toolTip.hidetip() 50 | widget.bind('', enter) 51 | widget.bind('', leave) 52 | -------------------------------------------------------------------------------- /Chapter11/Ch11_Code/__init__.py: -------------------------------------------------------------------------------- 1 | print('hi from GUI init\n') 2 | from sys import path 3 | from pprint import pprint 4 | #======================================================= 5 | # Required setup for the PYTONPATH in order to find 6 | # all package folders 7 | #======================================================= 8 | from site import addsitedir 9 | from os import getcwd, chdir, pardir 10 | for _ in range(10): 11 | curFull = getcwd() 12 | curDir = curFull.split('\\')[-1] 13 | if 'Ch11_Code' == curDir: 14 | addsitedir(curFull) 15 | addsitedir(curFull + '\\Folder1\\Folder2\\Folder3\\') 16 | break 17 | chdir(pardir) 18 | pprint(path) 19 | #======================================================= 20 | 21 | -------------------------------------------------------------------------------- /Chapter11/Ch11_Code/pyc.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Python-GUI-Programming-Cookbook-Second-Edition/1ca9866be88b4191a5a951cbc4ead7aad903f226/Chapter11/Ch11_Code/pyc.ico -------------------------------------------------------------------------------- /Instructions: -------------------------------------------------------------------------------- 1 | The code has been tested on the latest version of Eclipse which is NEON. 2 | Version: Neon.1a Release (4.6.1) 3 | 4 | It has been tested on Windows 10. 5 | It is expected to run well on Apple Macintosh but we did not test this. 6 | 7 | The PyDev version within Eclipse is the latest, which is: 8 | 5.3.1.201610311318 9 | 10 | Python version used was 3.6.0. 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Packt 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ## $5 Tech Unlocked 2021! 5 | [Buy and download this Book for only $5 on PacktPub.com](https://www.packtpub.com/product/python-gui-programming-cookbook-second-edition/9781787129450) 6 | ----- 7 | *If you have read this book, please leave a review on [Amazon.com](https://www.amazon.com/gp/product/1787129454). Potential readers can then use your unbiased opinion to help them make purchase decisions. Thank you. The $5 campaign runs from __December 15th 2020__ to __January 13th 2021.__* 8 | 9 | # Python GUI Programming Cookbook - Second Edition 10 | This is the code repository for [Python GUI Programming Cookbook - Second Edition](https://www.packtpub.com/application-development/python-gui-programming-cookbook-second-edition?utm_source=github&utm_medium=repository&utm_campaign=9781787129450), published by [Packt](https://www.packtpub.com/). It contains all the supporting project files necessary to work through the book from start to finish. 11 | ## About the Book 12 | This book will guide you from the very basics of creating a fully functional GUI in Python with only a few lines of code. Each and every recipe adds more widgets to the GUIs we are creating. While the cookbook recipes all stand on their own, there is a common theme running through all of them. As our GUIs keep expanding, using more and more widgets, we start to talk to networks, databases, and graphical libraries that greatly enhance our GUI’s functionality. This book is what you need to expand your knowledge on the subject of GUIs, and make sure you’re not missing out in the long run. 13 | ### Instructions and Navigations 14 | All of the codes are organized as per the chapters, each folder has the codes related to that chapter or appendix. 15 | For example: Python-GUI-Programming-Cookbook-Second-Edition/Chapter01/Ch01_Code/First_GUI.py 16 | 17 | The code will look like the following: 18 | ``` 19 | import tkinter as tk 20 | 21 | # Create instance 22 | win = tk.Tk() 23 | 24 | # Add a title 25 | win.title("Python GUI") 26 | ``` 27 | 28 | Following is the software-hardware list: 29 | 30 | | Chapter | Software required | Download links to the software | Hardware required | OS required | 31 | | ------------- | ------------- | ------------- | ------------- | ------------- | 32 | | All | Python 3.6 | https://www.python.org/downloads/release/python-360/ | Your PC | Windows 8 and up | 33 | 34 | ## Related Products 35 | 36 | 37 | * [Python GUI Programming Solutions [Video]](https://www.packtpub.com/application-development/python-gui-programming-solutions-video?utm_source=github&utm_medium=repository&utm_campaign=9781786465528) 38 | 39 | 40 | * [Python Parallel Programming Cookbook](https://www.packtpub.com/application-development/python-parallel-programming-cookbook?utm_source=github&utm_medium=repository&utm_campaign=9781785289583) 41 | 42 | 43 | * [Python Network Programming Cookbook](https://www.packtpub.com/networking-and-servers/python-network-programming-cookbook?utm_source=github&utm_medium=repository&utm_campaign=9781849513463) 44 | 45 | 46 | 47 | ### Download a free PDF 48 | 49 | If you have already purchased a print or Kindle version of this book, you can get a DRM-free PDF version at no cost.
Simply click on the link to claim your free PDF.
50 |

https://packt.link/free-ebook/9781787129450

--------------------------------------------------------------------------------