Tkintertoy Gallery¶
Date: Aug 07, 2023 Author: Mike Callahan
Introduction¶
In order to demostrate the capabilities of Tkintertoy, I wrote an sampler-type application that demonstrates how to use most of the widgets in the library, ttgallery. This application is a simple modify and collect program where and user interacts with the widgets and sees their selections in a text widget. It also shows two independent windows, one that uses ttk widgets, the other uses older tk widgets.
A Gallery of ttWidgets¶
Below is the code followed by an explanation of every line:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 #------------------------------------------------------------------------------- # Name: ttgallery.py # Purpose: Demostrate use of tkintertoy widgets # # Author: mike.callahan # # Created: 7/5/2023 # Copyright: (c) mike.callahan 2019 - 2023 # License: MIT #------------------------------------------------------------------------------- from tkintertoy import Window class Gui: def __init__(self): """ Create the windows """ self.gui = Window() self.gui2 = Window(extra=True) self.gui.setTitle('Tkintertoy Gallery') self.gui2.setTitle('Tk Only Window') self.makeGui() def makeGui(self): """ Create the main (ttk) window """ # a simple menu mymenu = self.gui.addMenu('ttmainmenu', self.gui.master) # create a main menu fmenul = [['command', {'label':'Open...', 'command':self.popOpen}], # create a file menu ['command', {'label':'Save As...', 'command':self.popSaveAs}], ['command', {'label':'Choose Directory...', 'command':self.popChooseDir}], ['command', {'label':'Exit', 'command':self.gui.cancel}]] mmenul = [['command', {'label':'About', 'command':self.popAbout}], # create a misc menu ['command', {'label':'ChooseColor', 'command':self.popColor}]] fmenuc = self.gui.addMenu('ttfmenu', mymenu, fmenul) # create sub menus mmenuc = self.gui.addMenu('ttmmenu', mymenu, mmenul) mymenu.add('cascade', label='File', menu=fmenuc) # add them to the main menu mymenu.add('cascade', label='Misc', menu=mmenuc) self.gui.master['menu'] = mymenu # connect the main menu to the window # Notebook tabs = ['Simple','Dialog','Multi','Other'] # label the tabs self.pages = self.gui.addNotebook('ttnotebook', tabs) # create the notebook # Text Box self.gui.addText('ttext', 'Text Box', width=60, height=10) # create text area self.gui.plotxy('ttext', 0, 1) # Progress Bar self.gui.addProgress('ttprogress', 'Progress Bar', length=200) # create progrees bar self.gui.plotxy('ttprogress', 0, 2) # Command Buttons cmd = [['Collect',self.collect],['Exit', self.gui.cancel]] # create two buttons self.gui.addButton('ttbutton', '', cmd) self.gui.plotxy('ttbutton', 0, 3) # Notebook Pages self.makeSimple() self.makeDialog() self.makeMulti() self.makeOther() self.gui.plotxy('ttnotebook', 0, 0) self.gui.set('ttnotebook', 'Simple') # select first page self.makeGui2() def makeSimple(self): """ Create the page with the most common widgets """ self.simplePage = self.pages[0] # Label self.simplePage.addLabel('ttlabel', '', 'bold', # create a label with an text='This is a BOLD label') # initial text self.simplePage.plotxy('ttlabel', 0, 0) # Line self.simplePage.addLine('ttline') # create a horizontal line self.simplePage.plotxy('ttline', 0, 1, sticky='we') # stretch it horizontally # Entry self.simplePage.addStyle('g.TEntry', foreground='green') # create a green entry self.simplePage.addEntry('ttentry', 'Entry', style='g.TEntry') self.simplePage.set('ttentry', 'Green Text') # add the text self.simplePage.plotxy('ttentry', 0, 3) # Combobox acombo = ['ComboOption1','ComboOption2','ComboOption3'] self.simplePage.addCombo('ttcombo', 'Combo Box', acombo) # create combobox self.simplePage.plotxy('ttcombo', 0, 5) # Checkboxes achecks = ['CheckOption1','CheckOption2','CheckOption3'] self.simplePage.addCheck('ttchecks', 'Check Box', achecks) # create 3 checkboxes self.simplePage.set('ttchecks','checkOption1') # preselect first checkbox self.simplePage.plotxy('ttchecks', 0, 6) self.simplePage.setState('ttchecks', ['disabled'], index=1) # disable CheckOption2 # Radio Buttons aradio = ['RadioOption1','RadioOption2','RadioOption3'] self.simplePage.addRadio('ttradio', 'RadioButton Box', aradio) # create 3 radiobuttons self.simplePage.plotxy('ttradio', 0, 7) # Scale self.simplePage.addScale('ttscale', [1,10], 'Scale', width=2, length=200) # create a scale self.simplePage.plotxy('ttscale', 0, 8) # Spinners adate = [[2,1,12],[2,1,31],[4,2000,2099]] self.simplePage.addSpin('ttspin', adate, '/', 'Date Box') # create a date entry box self.simplePage.set('ttspin', '4/21/2023') # set the initial date self.simplePage.plotxy('ttspin', 0, 9) def makeDialog(self): """ Create the dialog widget page """ self.dialogPage = self.pages[1] # Open self.dialogPage.addOpen('ttopen', 'Open', width=40) # open dialog self.dialogPage.plotxy('ttopen', 0, 0) # SaveAs self.dialogPage.addSaveAs('ttsaveas', 'Save As', width=40) # save as dialog self.dialogPage.plotxy('ttsaveas', 0, 1) # ChooseDir self.dialogPage.addChooseDir('ttchoosedir', 'Choose Dir', width=40) # choose dir dialog self.dialogPage.plotxy('ttchoosedir', 0, 2) def makeMulti(self): """ Create the multi use widget page """ self.multiPage = self.pages[2] # Listbox alist = ['ListOption1','ListOption2','ListOption3'] self.multiPage.addList('ttlist', 'List', alist, height=4, selectmode='multiple') # create list self.multiPage.plotxy('ttlist', 0, 0) # Ledger cols = [['column1',100],['column2',80],['column3',80]] self.multiPage.addLedger('ttledger', cols, 'Ledger', height=4) # create ledger self.multiPage.set('ttledger', [['item0-0','item1-0','item2-0']]) self.multiPage.set('ttledger', [['item0-1','item1-1','item2-1']]) self.multiPage.set('ttledger', [['item0-2','item1-2','item2-2']]) self.multiPage.plotxy('ttledger', 0, 1) # Collector self.subwin = self.multiPage.addFrame('ttframe', '', relief='groove') # -Combobox acombo = ['ComboOption2-1','ComboOption2-2','ComboOption2-3'] self.subwin.addCombo('ttcombo2', 'Combo Box 2', acombo) self.subwin.plotxy('ttcombo2', 0, 0) # -Radio Button aradio = ['Radio2-1','Radio2-2','Radio2-3'] self.subwin.addRadio('ttradio2', 'RadioButton Box 2', aradio) self.subwin.plotxy('ttradio2', 0, 1) # -Collector cols = [['Combo',110],['Radio', 90]] self.subwin.addCollector('ttcollector', cols, ['ttcombo2','ttradio2'], 'Collector', height=4) self.subwin.plotxy('ttcollector', 0, 2) self.multiPage.plotxy('ttframe', 0, 2) def makeOther(self): """ Create page with the leftover widgets """ self.otherPage = self.pages[3] # Canvas canvas = self.otherPage.addCanvas('ttcanvas', 'Canvas', width=300, height=100) # create canvas canvas.create_oval(10, 10, 290, 90, fill='green') self.otherPage.plotxy('ttcanvas', 0, 0) # Multipane paneTitles = ['Pane 1','Pane 2','Pane 3'] panes = self.otherPage.addPanes('ttpane', paneTitles, orient='horizontal') for i in range(3): # -Label tag = 'ttlabel' + str(i) panes[i].addLabel(tag) panes[i].set(tag, f'Inner label {i+1}') panes[i].plotxy(tag) self.otherPage.plotxy('ttpane', 0, 1) def popOpen(self): """ Open dialog """ self.gui.set('ttext', self.gui.popDialog('askopenfilename', title='Open a File')+'\n') def popSaveAs(self): """ Save As dialog """ self.gui.set('ttext', self.gui.popDialog('asksaveasfilename', title='Save a File')+'\n') def popChooseDir(self): """ Choose Directory dialog """ self.gui.set('ttext', self.gui.popDialog('askdirectory', title='Select a Directory')+'\n') def popColor(self): """ Choose Color dialog """ self.gui.set('ttext', str(self.gui.popDialog('askcolor', title='Select a Color'))+'\n') def popAbout(self): """ Pop Up an About window """ self.gui.popMessage('Tkintertoy Gallery\nMost of the widgets in Tkintertoy.') def makeGui2(self): """ Fill a second independent window using tk widgets only """ # Label self.gui2.addLabel('ttlabel2',usetk=True, text='These are Tk widgets.', effects='bold') # Entry self.gui2.addEntry('ttentry2','Type something here', usetk=True, foreground='blue', background='yellow') # Checkboxes achecks = ['CheckOption1','CheckOption2','CheckOption3'] self.gui2.addCheck('ttchecks2', 'Check Box', achecks, usetk=True) # create 3 checkboxes self.gui2.set('ttchecks2','CheckOption3') # preselect first checkbox # Radio Buttons aradio = ['RadioOption1','RadioOption2','RadioOption3'] self.gui2.addRadio('ttradio3', 'RadioButton Box', aradio, usetk=True) # create 3 radiobuttons self.gui2.set('ttradio3', 'RadioOption2') # Message self.gui2.addMessage('ttmessage', 'Message', justify='center') # create a message self.gui2.set('ttmessage', 'Useful for multi-line messages,\n' 'like this one.') # add the text # Option alist = ['Option1','Option2','Option3'] self.gui2.addOption('ttoption', 'Option List', alist) # create an option list self.gui2.set('ttoption', 'Option1') # Scale self.gui2.addScale('ttscale2', [1,10], 'Scale', width=2, usetk=True, orient='horizontal', length=200) # create a scale # Spinners adate = [[2,1,12],[2,1,31],[4,2000,2099]] self.gui2.addSpin('ttspin2', adate, '/', 'Date Box', usetk=True) # create a date entry box self.gui2.set('ttspin2', '3/15/2001') # set the initial date # Buttons cmd = [['Collect',self.collect2],['Close', self.gui2.close]] # create two buttons self.gui2.addButton('ttbutton2', '', cmd, usetk=True) # Plot widgets self.gui2.plotxy('ttlabel2', 0, 0, padx=30) self.gui2.plotxy('ttentry2', 0, 1) self.gui2.plotxy('ttchecks2', 0, 2) self.gui2.plotxy('ttradio3', 0, 3) self.gui2.plotxy('ttmessage', 0, 4) self.gui2.plotxy('ttoption', 0, 5) self.gui2.plotxy('ttscale2', 0, 6) self.gui2.plotxy('ttspin2', 0, 7) self.gui2.plotxy('ttbutton2', 0, 8, pady=10) def collect(self): """ Show contents of all widgets on the main (ttk) page """ result = '\nMain Window\n Simple Page:\n ' result += self.simplePage.get('ttlabel') + '\n ' result += self.simplePage.get('ttentry') + '\n ' result += self.simplePage.get('ttcombo') + '\n ' result += str(self.simplePage.get('ttchecks')) + '\n ' result += self.simplePage.get('ttradio') + '\n ' result += str(self.simplePage.get('ttscale')) + '\n ' result += self.simplePage.get('ttspin') + '\n ' self.gui.set('ttprogress', 33) self.gui.set('ttext', result) self.gui.master.after(1000) # wait one sec result = ' Dialog Page:\n ' result += self.dialogPage.get('ttopen') + '\n ' result += self.dialogPage.get('ttsaveas') + '\n ' result += self.dialogPage.get('ttchoosedir') + '\n ' self.gui.set('ttprogress', 66) self.gui.set('ttext', result) self.gui.master.after(1000) # wait one sec result = ' Multi Page:\n ' result += str(self.multiPage.get('ttlist')) + '\n ' result += str(self.multiPage.get('ttledger')) + '\n ' result += str(self.subwin.get('ttcollector', allValues=True)) + '\n ' result += f"{self.gui.get('ttnotebook')} page selected\n" result += '\n\n' self.gui.set('ttprogress', 100) self.gui.set('ttext', result) self.gui.master.after(1000) # wait one sec self.gui.set('ttprogress', 0) def collect2(self): """ Collect the infomation from the second window and place in ttext """ result = '\nSecond Window:\n ' result += self.gui2.get('ttlabel2')+'\n ' result += self.gui2.get('ttentry2')+'\n ' result += str(self.gui2.get('ttchecks2'))+'\n ' result += self.gui2.get('ttradio3')+'\n ' result += self.gui2.get('ttmessage') + '\n ' result += self.gui2.get('ttoption') + '\n ' result += str(self.gui2.get('ttscale2'))+'\n ' result += self.gui2.get('ttspin2')+'\n\n' self.gui.set('ttext', result) def main(): """ main driving function """ app = Gui() try: app.gui.waitforUser() except: # trap all Exceptions errorMessage = app.gui.catchExcept() app.gui.popMessage(errorMessage, 'showwarning', 'Error') app.gui.cancel() if __name__ == '__main__': main()
Here is an explanation of what each line does:
- Documentation of application.
- Same.
- Same.
- Same.
- Same.
- Same.
- Same.
- Same
- Same.
- Same.
- Blank line.
- Import the
Window
code which is the foundation of Tkintertoy. - Blank line.
- Create the
Gui
class. We will use composition style so we are not inheriting from any other class.self
will be the application. - Blank line.
- __init__. This method creates the windows, sets the
titles, then calls the
makegui
method. - Method documentation.
- Create a Window and assign it as an attribute,
gui
. - Create a second independent Window and assign it as an attribute,
gui2
. - Set the title of
gui
. - Set the title of
gui2
. - Call
makeGui
which will fill the windows with widgets. - Blank line.
- makeGui. This method creates and places all the widgets in the main (ttk)
window and then calls
makeGui2
. - Method documentation.
- This is the ttMenu creation section. Menus are good for placing command options in a pulldown structure. These can be quite complex so this is a simple example. Read the Tkinter documentation for more information.
- Create a ttMenu as the main menu,
mymenu
attached to themaster
attribute to the main window,gui
. This shows in general how to add a Tkintertoy widget to a window. The first argument is a unique tag for the widget, ‘ttmainmenu’. You will use this tag to work with the widget. In this application all tags start with ‘tt’ but tags can be any string. - Create a file menu list,
fmenul
, the first option is ‘Open…’ which is connected to thepopOpen
method… - The second option is ‘Save AS…’ which is attached to the
popSaveAs
method… - The third option is ‘Choose Directory’ which is connected to the
popChooseDir
method… - The fourth option is ‘Exit’ whic is attached to the
cancel
method ofgui
. This method is included with all Tkintertoy windows. - Create a misc menu list,
mmenul
, the first option is ‘About’ which is attached to thepopAbout
method… - The second option is ‘ChooseColor’ which is attached to the
popColor
method. - Create the file menu,
fmenuc
, attached to the main menu usingfmenul
. - Create the misc menu,
mmenuc
, attached to the main menu usingmmenul
. - Add
fmenuc
as a cascade (pulldown) under the ‘File’ label ofmymenu
. - Add
mmenuc
as a cascade under the ‘Misc’ label ofmymenu
. - Add
mymenu
to themenu
option of the master attribute ofgui
. This will make the ‘File’ and ‘Misc’ labels appear at the top of the window. - This is the ttNotebook creation section. Notebooks are a collection of windows, called pages, stacked on top of each other accessed by a tab at the top of the window. It is a good way to save on screen space and hide groups of widgets. Notebooks are a ttk only widget which have no frame.
- Create a list of tabs,
tabs
. - Create a ttNotebook using
tabs
with a tag of ‘ttnotebook’. Store the list of pages in thepages
attribute. Each tab will create its own page. - This is the ttText section. The text widget includes vertical scrollbars
and is an extremely powerful widget with lots of uses. You can think of it as
the replacement for the
print
function in command-line scripts. Text is a tk only widget. Read the Tkinter documentation for more information. - Add a ttText widget 60 characters wide by 10 characters high to
gui
. The first argument is tag, ‘ttext’. The second argument is the text for the widget frame. Most Tkintertoy widgets have frames (menus and notebooks do not have frames) in which you can change the appearance. Frames are a great place for user prompts. The other arguments are keyword arguments which define the widget. In most cases, we do not need to save the widget in a variable, the tag does this for us. - Plot it at column 0, row 1. The notebook will be at 0, 0. This shows how to
place a ttWidget in a window. The first argument is the widget tag, the
second argument in the column or x position, and the third argument is the
row or y position. Following this are keyword arguments that modify the placement
of the widgets. Widgets will not appear until they are plotted. Note, in
Tkintertoy, widget creation and widget placement are two different method
calls. You can plot the widgets immediately after creation like this method,
or you can collect all the
plotxy
calls at the end of the method as you will see in a later method. - This is the ttProgressbar creation section. Progress bars show the user what percentage of time is left elapsed during a long operation. Progress bars are a ttk only widget. We will see how to update a progress bar in the data collection method.
- Create a ttProgressbar that is 200 pixels wide with a tag of ‘ttprogress’.
- Plot it at column 0, row 2.
- This is the ttButtonbox creation section. Buttonboxes are groups of buttons connected to commands. These are the widgets that make actions happen when user click on them.
- Create a button list,
cmd
, which has two labels (‘Collect’ and ‘Exit’) and the linked methods (collect
andcancel
). - Create a ttButtonbox using
cmd
, with a tag of ‘ttbutton’. - Plot it at column 0, row 3.
- This is the ttNotebook pages creator section. Each page has its own creation method.
- Create the first page, ‘Simple’.
- Create the second page, ‘Dialog’.
- Create the third page, ‘Multi’.
- Create the fourth page, ‘Other’.
- Plot the notebook at column 0, row 0. Note, we filled the notebook pages before we plotted the notebook.
- Set the displayed tab to ‘Simple’.
- Create the second window. We will fill this window with ttWidgets that set the keyword option usetk=True so you can see the difference between tk and ttk widgets. In some cases, working with ttk widgets is more complex and the visble difference may not be worth the hassle. A good example of this is the ttEntry widget.
- Blank line.
- makeSimple. This is the method that fills the first notebook page, ‘Simple’. This page will contain the most commonly used widgets that are easy to implement.
- Method documentation.
- Create an attribute to store the first page window,
simplePage
. - This is the ttLabel secton. Labels are a good place to put data or images that don’t change.
- Add a ttLabel on the first page with bold text, with a tag of ‘ttlabel’. Note,
if you use the text keyword argument, you can specify the contents at creation,
you don’t have to use the
set
method. It does make the method call a bit long, however. - Same.
- Plot it at column 0, row 0. Notice that the columns and rows of
simplePage
are different fromgui
. - This is the ttLine section. Lines are vertical or horizontal which seperate groups of widgets. This is a ttk only widget which has no frame.
- Add a horizontal ttLine to the page, with a tag of ‘’ttline’.
- Plot it at column 0, row 1, stetching across the page. If we did not use the sticky=’we’ keyword argument, it would have plotted a single point!
- This is the ttEntry section. The entry widget allows the user to type in
a response. You can think of it as a replacement from the
input
function in command-line scripts. - Add a ttStyle for a ttEntry with green text, with a tag of ‘g.TEntry’. The tag must end with ‘.TEntry’ since this is a style for an entry widget. To change he appearance of a ttk.Entry, you must use a style. With tk.Entrys this is not neccessary as you will see in the tk window. However, this style can be used for multiple entries.
- Add a ttEntry using the ‘g.TEntry’ style, with a tag of ‘ttentry’. Note, the difference between the tag of the entry and the tag for the style.
- Set the entry contents to ‘Green Text’. This string will appear as green because of the style argument.
- Plot it at column 0, row 3
- This is the ttCombobox section. Comboboxes are a combination of a entry and a list. They are good for giving the user a fixed set of options but allowing them to create their own.
- Create a combobox option list,
acombo
. - Add a ttCombobox using
acombo
, with tag a of ‘ttcombo’. - Plot it at column 0, row 5.
- This is the ttCheckbox section. Checkboxes are a good way of letting the user select multiple independent options.
- Create a list of checkbox options,
achecks
. - Add a ttCheckbox using
achecks
, with a tag of ‘ttchecks’. - Set the selected option to ‘CheckOption1’. Note that multiple options can be selected at a time.
- Plot it at column 0, row 6.
- Disable the second option (‘CheckOption2’) from being selected. This demonstrates how to change the state of a widget. To enable, you would set the state to [‘!disabled’].
- This is the Radiobox section. Radioboxes are a good way of letting the user select a single option from a group of dependent options.
- Create a list of options,
aradio
. - Add a ttRadiobox using
aradio
with a tag of ‘ttradio’. Note, only a single option can be selected at a time. - Plot it at column 0, row 7.
- This is the ttScale section. Scales are a good widget for single integer entry if the range is small.
- Add a horizontal ttScale that goes between 1 and 10, that has an entry width of 2 characters, a length of 200 pixels, with a tag of ‘ttscale’.
- Plot it at column 0, row 8.
- This is the ttSpinbox section. Spinboxes are a great way to enter a group of related integers in a particular format like dates, times, ss numbers, etc.
- Create a date list for month, date, and year,
adate
. The first option is the width, the second the minimum value, and the third the maximum value. - Add a ttSpinbox for dates that runs from 1/1/2000 to 12/31/2099, with a tag of ‘ttspin’.
- Set the date to 4/21/2023. Note, the
set
method requires a string with the separators. - Plot it at column 0, row 9.
- Blank line.
- makeDialog. Create the method that fills the ‘Dialog’ page. These widgets use the built-in tk dialog widgets.
- Method documentation.
- Create an attribute to store the second page window,
dialogPage
. - This is the ttOpen dialog section. This is how the user can select A file to open.
- Add a ttOpen with an entry width of 40 characters with a tag of ‘ttopen’.
- Plot it on the ‘Dialog’ page at column 0, row 0.
- This is the ttSaveAs dialog section. This is how the user can select a file to save their work. If the filename already exists, a confirming overwrite dialog pops up.
- Add a ttSaveAs with an entry width of 40 characters with a tag of ‘ttsaveas’.
- Plot it at column 0, row 1.
- This is the ttChooseDir dialog section. This allows the user to select a working directory.
- Add a ttChooseDir with an entry width of 40 characters with a tag of ‘ttchoosedir’.
- Plot it at column 0, row 2.
- Blank line.
- makeMulti. This is the method that fills the ‘Multi’ page. This page will contain more complex widgets.
- Method documentation.
- Create an attribute to store the third page window,
multiPage
. - This is the ttListbox section. While an older tk only widget, listboxes are still very useful. They can be configured to allow a single or multiple option section.
- Create a list of listbox options,
alist
. - Add a ttlistbox that uses
alist
, that is 4 characters high, with a tag of ‘ttlist’. Listboxes default to single selection like a radiobox so we are changing this using selectmode=’multiple’. - Plot it on the ‘Multi’ page at column 0, row 0.
- This is the ttLedger section. Ledger is a new widget based on a a ttk.Treeview. It is good for displaying multicolumn data. it includes a vertical scrollbar. Horizontal scrolling in treeview does not work so if you need horizontal scrolling use a text widget.
- Create a list of lists,
cols
, that contain the column header and width in pixels. - Add a ttLedger, using
cols
, with height of 4 characters and a tag of ‘ttledger’. - Add a line of data to the Ledger.
- Same.
- Same.
- Plot it at column 0, row 1.
- This the ttCollector section. This is a new complex widget combining multiple widgets and a ledger with 2 command buttons, ‘Add’ and ‘Delete’. In this example, we will combine a combobox and a radiobox box. It acts like a dialog inside of a dialog.
- We are going to add a ttFrame with a tag of ‘ttframe’, and place all
the widgets connected to the collection inside. It will be referenced by
an attribute
subframe
. - This is the ttCombobox section for the collector.
- Create a list of combobox options,
acombo
. - Add a ttCombobox using
acombo
with a tag of ‘ttcombo2’. Note, While we reusedacombo
for a different list of options, the tag ‘ttcombo2’ is unique. We are doing this to eliminate any confusion in the code when we collect the widgets. However, we could have used the same tag since each window keeps its own dictionary of tags. - Plot it at column 0, row 0 in
subframe
. - This is the ttRadiobox section for the collector.
- Create a list of radiobox options,
aradio
. - Create a ttRadioBox using
aradio
with a tag of ‘ttradio2’. - Plot it at column 0, row 1.
- This is the ttCollector section. This will connect the above widgets to the collector.
- Create a list of lists,
cols
, that has the column headers and the width in pixels. - Create the ttCollector using
cols
and the list of connected widgets tags, that is 4 characters high, with a tag of ‘ttcollector’. Note, the connected widgets must be created before the collector is created. - Same.
- Plot the collector at column 0, row 2 of
subwin
. - Plot
subwin
(which has a tag ‘ttframe’) at column 0, row 2 ofmultiPage
. Note how the arguments ofplotxy
are dependent on the current container you are working with and when plotting frames you use the tag. - Blank line.
- makeOther. This method fills the ‘Other’ page. This page will contain widgets that are not in the first three pages.
- Method documentation.
- Create an attribute to store the fourth page window,
otherPage
. - The is the ttCanvas section. Canvas is a powerful tk widget that allows you to create drawings. It has extensive methods which are listed in the Tkinter documentaton. In this example, we are going to draw a simple green oval.
- Add a ttCanvas that is 300 pixels wide and 100 pixels high, with a tag of
‘ttcanvas’ and save it under
canvas
. Almost alladdWidget
calls return the ttk or tk widget but most of the time, we don’t need it becasue we reference the widget through the tag. In this case, we are going to store the canvas widget in a local varaible,canvas
, since we are going to call a method of the widget. We are using a local variable since we are not going the access this widget outside this method. We could have also accessed the canvas widget usinggetWidget('ttcanvas')
. - Same.
- Create a green oval at position (10,10) that is 290 pixels wide and 90 pixels
high by calling the
create_oval
method ofcanvas
. - Plot this canvas at column 0, row 0 on
otherPage
. - This is the ttMultipane section. Multipanes are multiple windows placed overlapping each other that can be re-sized.
- Create a list of pane titles,
paneTitles
. - Add a ttMultipane using
paneTitles
with a tag of ‘ttpane’’. The default orientation is vertical so this is why we are using the orient=’horizontal’ keyword argument. Note, the method will return a list of 3 windows, which we will store inpanes
. - Set up a loop running from 0 to 2…
- This is the ttlabel section of the multipane. We want to place a single label in each pane.
- Create a dynamic tag that looks like ‘ttlabeln’, where n is 0-2.
- Add a label with the above tag in the correct window.
- Set the contents of the label like this: ‘Inner label n’ where n is 1-3.
- Plot the label in the column 0, row 0 of the correct window.
- Plot the multipane in column 0, row 1, of
otherPage
. - Blank line.
- popOpen. This method pops-up an open dialog. Note,the next 4 methods all call the same method. Only the arguments are different. These are the methods that the menu options are connected to.
- Method documentation.
- Pop-up an open dialog. Display the user’s entry ‘ttext’.
- Same.
- Blank line.
- popSaveAs. This method pops-up a save as dialog.
- Method documentation.
- Pop-up a save as dialog. Display the user’s entry in ‘ttext’.
- Same.
- Blank line.
- popChooseDir. This method pops-up a choose directory dialog.
- Method documentation.
- Pop-up a choose directory dialog. Display the user’s entry in ‘ttext’.
- Same.
- Blank line.
- popColor. This method pops-up a choose color dialog.
- Method documentation.
- Pop-up a choose color dialog. Display the user’s entry in ‘ttext’.
- Same.
- Blank line.
- popAbout. This method pops-up an about window. This is where you put information about your application.
- Method documentation.
- Pop-up a message window. Note, you don’t use a tag or store anything
- Blank line.
- makeGui2. This method fills in the second window with tk versions of ttWidgets. This way you can see the difference between the two type of widgets
- Method documentation.
- This is the ttLabel section.
- Add a ttLabel to
gui2
with the keyword argument usetk=True and a tag of ‘ttlabel2. This will use tk widgets instead of ttk widgets. You will see this argument repeated for every widget ingui2
. The number of keyword arguments is greater with tk widgets since some of those options were sent to the style method in the ttk version. Read the Tkinter documentation for more information. Note, tk widgets are in the front of the documentation and not all tk widgets have ttk versions. - Same.
- This is the ttEntry section.
- Add a ttEntry to
gui2
with of ‘ttentry2’. Note, you can specify the foreground and background colors as keyword arguments so styles are not required to change default colors. - Same.
- This is the ttCheckbox section.
- Create a list of checkbox options,
achecks
. - Add a group of checkboxes using
achecks
with a tag of ‘ttchecks2’. - Preselect the third option.
- This is the ttRadiobox section.
- Create a list of radiobox options,
aradio
. - Add a ttRadiobox to
gui2
with a tag of ‘ttradio3’. - Preselect the second option.
- This is the ttMessage section. This is a tk only widget good for displaying multiple lines of text.
- Add a ttMessage widget center justified with a tag of ‘ttmessage’.
- Set the message content.
- Same.
- This is the option list section. This is an older tk only widget, similar to a combox without the entry widget.
- Create a list of options,
alist
. - Add a ttOptionlist using
alist
with a tag of ‘ttoption’. - Set the selected option to ‘Option1’. Note, like a radiobox, only a single option can be selected at a time.
- This is the ttScale section.
- Add a horizontal ttScale that goes between 1 and 10, that has an entry width of 2 characters and a length of 200 pixels and a tag of ‘ttscale2’.
- Same.
- This is the ttSpinbox section.
- Create a date list for month, date, and year,
adate
. The first value is the width in characters, the second is the minimum value, and the third is the maximum value. - Add a ttSpinbox for dates that runs from 1/1/2000 to 12/31/2099 with a tag of ‘ttspin2’.
- Set the date to 3/15/2021
- This is the ttButtonbox creation section.
- Create a button list,
cmd
, which has two labels (‘Collect’ and ‘Close’) and the linked methods (collect2
andclose
). Unlikecancel
,close
will close the window but the apllication will contune to run. - Create a ttButtonbox using
cmd
with a tag of ‘ttbutton2’. - This is the widget plotting section. In
makeGui
we plotted the widgets as soon as we created them. Here we are going the plot all the widgets at the end of the method. Some programmers like this technique because they can experiment with the placement of widgets easier. - Plot ‘ttlabel2’ at column 0, row 0.
- Plot ‘ttentry2’ at column 0, row 1.
- PLot ‘ttchecks2’ at column 0, row 2.
- PLot ‘ttradio3’ at column 0, row 3.
- PLot ‘ttmessage’ at column 0, row 4.
- Plot ‘ttoption’ at column 0, row 5.
- Plot ‘ttscale2’ at column 0, row 6.
- Plot ‘ttspin2’ at column 0, row 7.
- Plot ‘ttbutton2’ at column 0, row 8, with a 10 pixel vertical spacing.
- Blank line.
- collect. This method collects all the contents of the
gui
window. To get the contents of any widget, you call theget
method on the window with the tag as the argument. You don’t have to worry about the type of widget,get
handles this automatically. - Method documentation.
- Build a string that will contain the widget contents,
result
. The header will indication that these are widgets fromsimplePage
. - Get the contents of ‘ttlabel’ and add to
result
. - Get the contents of ‘ttentry’ and add to
result
. - Get the contents of ‘ttcombo’ and add to
result
. - Get the contents of ‘ttchecks’ and add to
result
. Note, since checkboxes can have multiple values,get
returns a list, so we must convert it to a string. - Get the contents of ‘ttradio’ and add to
result
. - Get the contents of ‘ttscale’ and add to
result
. Note, sinceget
returns a int we must convert it to a string. - Get the contents of ‘ttspin’ and add to
result
. - We have collected about a third of the widgets so lets move the ‘’ttprogress’
to the 33% position. To change the contents of any widget you use the
set
method on the window with the tag as the first argument and the value as the second argument. Again, you don’t have to worry about the type of widget,set
handles this automatically. - Update ‘ttext’ with
result
. - Wait one second so the user can see the ‘ttprogress’ change. The
after
method of the master attribute has a number of very important uses. Read the Tkinter documentation for more information. - Create a new
result
fordialogPage
. - Get the contents of ‘ttopen’ and add to
result
. - Get the contents of ‘ttsaveas’ and add to
result
. - Get the contents of ‘ttchoosedir’ and add to
result
. - We have collected about two-thirds of the widgets so lets move the ‘’ttprogress’ to the 66% position.
- Update ‘ttext’ with
result
. - Wait one second so the user can see the ‘ttprogress’ change.
- Create a new
result
formultiPage
. - Get the contents of ‘ttlist’ and add to
result
. Note, since listboxes can have multiple values,get
returns a list, so we must convert it to a string. - Get the contents of ‘ttledger’ and add to
result
. Note, since ledgers can have multiple values,get
returns a list, so we must convert it to a string. - Get the contents of ‘ttcollector’ and add to
result
. Collector can be a single or multi value widget. We want a multi-value so the keyword argument is allValues=True, Note, sinceget
returns a list, so we must convert it to a string. - Get the displayed page from ‘ttnotebook’ and add to
result
. - Complete
result
. - We have collected all of the widgets so lets move the ‘’ttprogress’ to the 100% position.
- Update ‘ttext’ with
result
. - Wait one second so the user can see the ‘ttprogress’ change.
- Result ‘ttprogess’ back to 0%.
- Blank line.
- collect2. This method collects all the contents of the
gui2
window. - Method documentation.
- Build a string that will contain the widget contents,
result
. The header will indication that these are widgets fromgui2
. - Get the contents of ‘ttlabel2’ and add to
result
. - Get the contents of ‘ttentry2’ and add to
result
. - Get the contents of ‘ttchecks2’ and add to
result
. Note, since checkboxes can have multiple values,get
returns a list, so we must convert it to a string. - Get the contents of ‘ttradio3’ and add to
result
. - Get the contents of ‘ttmessage’ and add to
result
. - Get the contents of ‘ttoption’ and add to
result
. - Get the contents of ‘ttscale2’ and add to
result
. Note, sinceget
returns a int we must convert it to a string. - Get the contents of ‘ttspin2’ and add to
result
. - Update ‘ttext’ with
result
.
- Update ‘ttext’ with
- Blank line.
- main. Common Python. This is the main driving functon.
- Function documentation.
- Create an instance of Gui,
app
. Note, that this will build all the windows. - Begin a try block. This part of the application could crash and we want to capture any error messages.
- Start the application loop and wait for the user to press a command button. This will continue to run until the user clicks on ‘Exit’.
- If an error occurs…
- Catch the error message in
errorMessage
. ThecatchExcept
method is included in all Tkintertoy windows. - Pop-up an message box containing
errorMessage
. - After the user click on ‘Ok’ in the message box, exit the program.
- Blank line.
- Standard Python. If you are not importing, excute
main
. - Same.
By looking at this code, the novice programmer should be able to use most of the Tkintertoy widgets for their own application. Be sure to also see the code examples in the tutorial for more information.
A Collection of Screenshots¶
Here are screen shots of the resulting GUI, the Simple page:
The Dialog page:
The Multi page:
The Other page:
The second (tk) window: