Guest User

Untitled

a guest
Jun 15th, 2019
417
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 164.17 KB | None | 0 0
  1.  
  2.  
  3.  
  4. # High Level API Calls - Popup's
  5.  
  6. "High level calls" are those that start with "Popup". They are the most basic form of communications with the user. They are named after the type of window they create, a pop-up window. These windows are meant to be short lived while, either delivering information or collecting it, and then quickly disappearing.
  7.  
  8. ## Popup Output
  9.  
  10. Think of the `Popup` call as the GUI equivalent of a `print` statement. It's your way of displaying results to a user in the windowed world. Each call to Popup will create a new Popup window.
  11.  
  12. `Popup` calls are normally blocking. your program will stop executing until the user has closed the Popup window. A non-blocking window of Popup discussed in the async section.
  13.  
  14. Just like a print statement, you can pass any number of arguments you wish. They will all be turned into strings and displayed in the popup window.
  15.  
  16. There are a number of Popup output calls, each with a slightly different look (e.g. different button labels).
  17.  
  18. The list of Popup output functions are:
  19. - Popup
  20. - PopupOk
  21. - PopupYesNo
  22. - PopupCancel
  23. - PopupOkCancel
  24. - PopupError
  25. - PopupTimed, PopupAutoClose
  26. - PopupNoWait, PopupNonBlocking
  27.  
  28. The trailing portion of the function name after Popup indicates what buttons are shown. `PopupYesNo` shows a pair of button with Yes and No on them. `PopupCancel` has a Cancel button, etc.
  29.  
  30. While these are "output" windows, they do collect input in the form of buttons. The Popup functions return the button that was clicked. If the Ok button was clicked, then Popup returns the string 'Ok'. If the user clicked the X button to close the window, then the button value returned is `None`.
  31.  
  32. The function `PopupTimed` or `PopupAutoClose` are popup windows that will automatically close after come period of time.
  33.  
  34. Here is a quick-reference showing how the Popup calls look.
  35.  
  36. ```
  37. sg.Popup('Popup') - Shows OK button
  38. sg.PopupOk('PopupOk') - Shows OK button
  39. sg.PopupYesNo('PopupYesNo') - Shows Yes and No buttons
  40. sg.PopupCancel('PopupCancel') - Shows Cancelled button
  41. sg.PopupOKCancel('PopupOKCancel') - Shows OK and Cancel buttons
  42. sg.PopupError('PopupError') - Shows red error button
  43. sg.PopupTimed('PopupTimed') - Automatically closes
  44. sg.PopupAutoClose('PopupAutoClose') - Same as PopupTimed
  45. ```
  46.  
  47. Preview of popups:
  48.  
  49. <p style="display: flex;justify-content: space-around;">
  50. <img src="https://user-images.githubusercontent.com/13696193/44957394-1380ab00-aea0-11e8-98b1-1ab7d7bd5b37.jpg">
  51. <img src="https://user-images.githubusercontent.com/13696193/44957400-167b9b80-aea0-11e8-9d42-2314f24e62de.jpg">
  52. <img src="https://user-images.githubusercontent.com/13696193/44957399-154a6e80-aea0-11e8-9580-e716f839d400.jpg">
  53. </p>
  54.  
  55. <p style="display: flex;justify-content: space-around;">
  56. <img src="https://user-images.githubusercontent.com/13696193/44957398-14b1d800-aea0-11e8-9e88-c2b36a248447.jpg">
  57. <img src="https://user-images.githubusercontent.com/13696193/44957397-14b1d800-aea0-11e8-950b-6d0b4f33841a.jpg">
  58. <img src="https://user-images.githubusercontent.com/13696193/44957396-14194180-aea0-11e8-8eef-bb2e1193ecfa.jpg">
  59. <img src="https://user-images.githubusercontent.com/13696193/44957595-9e15da00-aea1-11e8-8909-6b6121b74509.jpg">
  60. </p>
  61.  
  62. ```
  63. Popup(*args, Variable number of arguments you want to display
  64. button_color=None, Color of buttons (text_color, background_color)
  65. background_color=None, Color of background
  66. text_color=None, Color of text
  67. button_type=POPUP_BUTTONS_OK, Type of button layout
  68. auto_close=False, If True window will automatically close
  69. auto_close_duration=None, Number of seconds for autoclose
  70. non_blocking=False, If True returns immediately
  71. icon=DEFAULT_WINDOW_ICON, Icon to use on the taskbar
  72. line_width=None, Width of lines in characters
  73. font=None, Font to use for characters
  74. no_titlebar=False, If True no titlebar will be shown
  75. grab_anywhere=False, If True can move window by grabbing anywhere
  76. keep_on_top=False, If True window will be on top of other windows
  77. location=(None,None)): (x,y) coordinates to show the window
  78. ```
  79.  
  80.  
  81. The other output Popups are variations on parameters. Usually the button_type parameter is the primary one changed.
  82.  
  83. The choices for button_type are:
  84. ```
  85. POPUP_BUTTONS_YES_NO
  86. POPUP_BUTTONS_CANCELLED
  87. POPUP_BUTTONS_ERROR
  88. POPUP_BUTTONS_OK_CANCEL
  89. POPUP_BUTTONS_OK
  90. POPUP_BUTTONS_NO_BUTTONS
  91. ```
  92. Note that you should not call Popup yourself with different button_types. Rely on the Popup function named that sets that value for you. For example PopupYesNo will set the button type to POPUP_BUTTONS_YES_NO for you.
  93.  
  94.  
  95. #### Scrolled Output
  96. There is a scrolled version of Popups should you have a lot of information to display.
  97.  
  98. ```python
  99. PopupScrolled(*args, button_color=None, yes_no=False, auto_close=False, auto_close_duration=None, size=(None, None), location=(None, None), title=None, non_blocking=False)
  100. ```
  101. Typical usage:
  102.  
  103. ```python
  104. sg.PopupScrolled(my_text)
  105. ```
  106.  
  107.  
  108. ![scrolledtextbox 2](https://user-images.githubusercontent.com/13696193/43667324-712aa0d4-9745-11e8-83a9-a0d0570d0865.jpg)
  109.  
  110.  
  111. The `PopupScrolled` will auto-fit the window size to the size of the text. Specify `None` in the height field of a `size` parameter to get auto-sized height.
  112.  
  113. This call will create a scrolled box 80 characters wide and a height dependent upon the number of lines of text.
  114.  
  115. sg.PopupScrolled(my_text, size=(80, None))
  116.  
  117. Note that the default max number of lines before scrolling happens is set to 50. At 50 lines the scrolling will begin.
  118.  
  119. If `non_blocking` parameter is set, then the call will not blocking waiting for the user to close the window. Execution will immediately return to the user. Handy when you want to dump out debug info without disrupting the program flow.
  120.  
  121. ### PopupNoWait
  122.  
  123. The Popup call PopupNoWait or PopupNonBlocking will create a popup window and then immediately return control back to you. All other popup functions will block, waiting for the user to close the popup window.
  124.  
  125. This function is very handy for when you're **debugging** and want to display something as output but don't want to change the programs's overall timing by blocking. Think of it like a `print` statement. There are no return values on one of these Popups.
  126.  
  127.  
  128.  
  129. ## Popup Input
  130.  
  131. There are Popup calls for single-item inputs. These follow the pattern of `Popup` followed by `Get` and then the type of item to get. There are 3 of these input Popups to choose from, each with settings enabling customization.
  132.  
  133. - `PopupGetText` - get a single line of text
  134. - `PopupGetFile` - get a filename
  135. - `PopupGetFolder` - get a folder name
  136.  
  137. Use these Popups instead of making a custom window to get one data value, call the Popup input function to get the item from the user. If you find the parameters are unable to create the kind of window you are looking for, then it's time for you to create your own window.
  138.  
  139. ### PopupGetText
  140.  
  141. Use this Popup to get a line of text from the user.
  142.  
  143. ```
  144. PopupGetText(message,The message you wish to display with the input field
  145. default_text='', Text to initially fill into the input field
  146. password_char='', Passwork character if this is a password field
  147. size=(None,None), Size of the window
  148. button_color=None, Color to use for buttons (foreground, background)
  149. background_color=None, Background color for window
  150. text_color=None, Text color for window
  151. icon=DEFAULT_WINDOW_ICON, Icon to display on taskbar
  152. font=None, Font to use for text
  153. no_titlebar=False, If True no titlebar will be shown
  154. grab_anywhere=False, If True can grab anywhere to move the window
  155. keep_on_top=False, If True window will stay on top of other windows
  156. location=(None,None)) Location on screen to display window
  157. ```
  158.  
  159. ```python
  160. import PySimpleGUI as sg
  161.  
  162. text = sg.PopupGetText('Title', 'Please input something')
  163. sg.Popup('Results', 'The value returned from PopupGetText', text)
  164. ```
  165.  
  166. ![popupgettext](https://user-images.githubusercontent.com/13696193/44957281-8721b880-ae9e-11e8-98cd-d06369f4187e.jpg)
  167.  
  168. ![popup gettext response](https://user-images.githubusercontent.com/13696193/44957282-8721b880-ae9e-11e8-84ae-dc8bb30504a0.jpg)
  169.  
  170. ### PopupGetFile
  171.  
  172. Gets a filename from the user. There are options to configure the type of dialog box to show. Normally an "Open File" dialog box is shown
  173.  
  174. ```
  175. PopupGetFile(message, Message to show in the window
  176. default_path='', Path browsing should start from
  177. default_extension='', Which filetype is the default
  178. save_as=False, Determines which dialog box stype to show
  179. file_types=(("ALL Files", "*.*"),), Which filetypes are displayed
  180. no_window=False, if True no window is displayed except the dialog box
  181. size=(None,None), Size of window
  182. button_color=None, Color of buttons
  183. background_color=None, Color of window background
  184. text_color=None, Color of text in window
  185. icon=DEFAULT_WINDOW_ICON, Icon to show on taskbar
  186. font=None, Font to use
  187. no_titlebar=False, If True does not display a titlebar
  188. grab_anywhere=False, if True can grab window anywhere to move it
  189. keep_on_top=False, if True window will be on top of others
  190. location=(None,None)) Location on screen to show window
  191. ```
  192.  
  193. If configured as an Open File Popup then (save_as is not True) the dialog box will look like this
  194.  
  195. ![snag-0060](https://user-images.githubusercontent.com/13696193/46761050-9831c680-cca1-11e8-8de9-68b15efe2c46.jpg)
  196.  
  197. If you set the parameter save_As to True, then the dialog box looks like this:
  198.  
  199. ![snag-0061](https://user-images.githubusercontent.com/13696193/46761330-2b6afc00-cca2-11e8-953b-f6b5c5ce57f5.jpg)
  200.  
  201. If you choose a filename that already exists, you'll get a warning popup box asking if it's OK. You can also specify a file that doesn't exist. With an "Open" dialog box you cannot choose a non-existing file.
  202.  
  203. A typical call produces this window.
  204.  
  205. ```python
  206. text = sg.PopupGetFile('Please enter a file name')
  207. sg.Popup('Results', 'The value returned from PopupGetFile', text)
  208. ```
  209.  
  210. ![popupgetfile](https://user-images.githubusercontent.com/13696193/44957857-2fd31680-aea5-11e8-8eb7-f6b91c202cc8.jpg)
  211.  
  212. ### PopupGetFolder
  213.  
  214. The window created to get a folder name looks the same as the get a file name. The difference is in what the browse button does. `PopupGetFile` shows an Open File dialog box while `PopupGetFolder` shows an Open Folder dialog box.
  215.  
  216. ```
  217. PopupGetFolder(message, Message to display in window
  218. default_path='', Path to start browsing
  219. no_window=False, If True no window will be shown
  220. size=(None,None), Size of window
  221. button_color=None, Color of buttons
  222. background_color=None, Background color of window
  223. text_color=None, Color of window text
  224. icon=DEFAULT_WINDOW_ICON, Icon to show on taskbar
  225. font=None, Font to use for window
  226. no_titlebar=False, If True no titlebar will be shown
  227. grab_anywhere=False, If True can grab anywhere on window to move
  228. keep_on_top=False, If True window will be on top
  229. location=(None, None)) Location on screen to create window
  230. ```
  231.  
  232. This is a typpical call
  233.  
  234. ```python
  235. text = sg.PopupGetFolder('Please enter a folder name')
  236. sg.Popup('Results', 'The value returned from PopupGetFolder', text)
  237. ```
  238.  
  239. ![popupgetfolder](https://user-images.githubusercontent.com/13696193/44957861-45484080-aea5-11e8-926c-cf607a45251c.jpg)
  240.  
  241.  
  242. ### PopupAnimated
  243.  
  244. ![ring](https://user-images.githubusercontent.com/13696193/51296743-6ee4ad00-19eb-11e9-91f5-cd8086ad1b50.gif)
  245.  
  246. The animated Popup enables you to easily display a "loading" style animation specified through a GIF file that is either stored in a file or a base64 variable.
  247.  
  248. ```python
  249. def PopupAnimated(image_source,
  250. message=None,
  251. background_color=None,
  252. text_color=None,
  253. font=None,
  254. no_titlebar=True,
  255. grab_anywhere=True,
  256. keep_on_top=True,
  257. location=(None, None),
  258. alpha_channel=.8,
  259. time_between_frames=0)
  260. ```
  261. | name | meaning |
  262. |-|-|
  263. |image_source | The GIF file specified as a string filename or a base64 variable |
  264. |message | optional text message to be displayed under the animation |
  265. |background_color | the background color to use for the window and all of the other parts of the window |
  266. |text_color | color to use for optional text |
  267. |font | font to use for the optional text |
  268. |no_titlebar | no titlebar window setting |
  269. |location | location to show the window |
  270. |alpha_channel | alpha channel to use for the window |
  271. |time_between_frames | amount of time in milliseconds to use between frames |
  272. |||
  273.  
  274. ***To close animated popups***, call PopupAnimated with `image_source=None`. This will close all of the currently open PopupAnimated windows.
  275.  
  276.  
  277. # Progress Meters!
  278. We all have loops in our code. 'Isn't it joyful waiting, watching a counter scrolling past in a text window? How about one line of code to get a progress meter, that contains statistics about your code?
  279.  
  280. ```
  281. OneLineProgressMeter(title,
  282. current_value,
  283. max_value,
  284. key,
  285. *args,
  286. orientation=None,
  287. bar_color=DEFAULT_PROGRESS_BAR_COLOR,
  288. button_color=None,
  289. size=DEFAULT_PROGRESS_BAR_SIZE,
  290. border_width=DEFAULT_PROGRESS_BAR_BORDER_WIDTH):
  291. ```
  292.  
  293. Here's the one-line Progress Meter in action!
  294.  
  295. ```python
  296. for i in range(1,10000):
  297. sg.OneLineProgressMeter('My Meter', i+1, 10000, 'key','Optional message')
  298. ```
  299.  
  300. That line of code resulted in this window popping up and updating.
  301.  
  302. ![preogress meter](https://user-images.githubusercontent.com/13696193/43667625-d47da702-9746-11e8-91e6-e5177883abae.jpg)
  303.  
  304. A meter AND fun statistics to watch while your machine grinds away, all for the price of 1 line of code.
  305. With a little trickery you can provide a way to break out of your loop using the Progress Meter window. The cancel button results in a `False` return value from `OneLineProgressMeter`. It normally returns `True`.
  306.  
  307. ***Be sure and add one to your loop counter*** so that your counter goes from 1 to the max value. If you do not add one, your counter will never hit the max value. Instead it will go from 0 to max-1.
  308.  
  309. # Debug Output
  310. Another call in the 'Easy' families of APIs is `EasyPrint`. It will output to a debug window. If the debug window isn't open, then the first call will open it. No need to do anything but stick a 'print' call in your code. You can even replace your 'print' calls with calls to EasyPrint by simply sticking the statement
  311.  
  312. ```python
  313. print = sg.EasyPrint
  314. ```
  315.  
  316. at the top of your code.
  317.  
  318. There are a number of names for the same EasyPrint function. `Print` is one of the better ones to use as it's easy to remember. It is simply `print` with a capital P.
  319.  
  320. ```python
  321. import PySimpleGUI as sg
  322.  
  323. for i in range(100):
  324. sg.Print(i)
  325. ```
  326.  
  327. ![snap0125](https://user-images.githubusercontent.com/13696193/43114979-a696189e-8ecf-11e8-83c7-473fcf0ccc66.jpg)
  328.  
  329. Or if you didn't want to change your code:
  330.  
  331. ```python
  332. import PySimpleGUI as sg
  333.  
  334. print=sg.Print
  335. for i in range(100):
  336. print(i)
  337. ```
  338.  
  339. Just like the standard print call, `EasyPrint` supports the `sep` and `end` keyword arguments. Other names that can be used to call `EasyPrint` include `Print`, `eprint`, If you want to close the window, call the function `EasyPrintClose`.
  340.  
  341. You can change the size of the debug window using the `SetOptions` call with the `debug_win_size` parameter.
  342.  
  343. There is an option to tell PySimpleGUI to reroute all of your stdout and stderr output to this window. To do so call EasyPrint with the parameter `do_not_reroute_stdout` set to True. After calling it once with this parameter set to True, all future calls to a normal`print` will go to the debug window.
  344.  
  345. If you close the debug window it will re-open the next time you Print to it.
  346.  
  347. ---
  348. # Custom window API Calls (Your First window)
  349.  
  350. This is the FUN part of the programming of this GUI. In order to really get the most out of the API, you should be using an IDE that supports auto complete or will show you the definition of the function. This will make customizing go smoother.
  351.  
  352. This first section on custom windows is for your typical, blocking, non-persistent window. By this I mean, when you "show" the window, the function will not return until the user has clicked a button or closed the window. When this happens, the window will be automatically closed.
  353.  
  354. Two other types of windows exist.
  355. 1. Persistent window - rather than closing on button clicks, the show window function returns and the window continues to be visible. This is good for applications like a chat window.
  356. 2. Asynchronous window - the trickiest of the lot. Great care must be exercised. Examples are an MP3 player or status dashboard. Async windows are updated (refreshed) on a periodic basis.
  357.  
  358. It's both not enjoyable nor helpful to immediately jump into tweaking each and every little thing available to you.
  359.  
  360. ## The window Designer
  361.  
  362. The good news to newcomers to GUI programming is that PySimpleGUI has a window designer. Better yet, the window designer requires no training, no downloads, and everyone knows how to use it.
  363.  
  364. ![gui0_1](https://user-images.githubusercontent.com/13696193/44159598-e2257400-a085-11e8-9b02-343e72cc75c3.JPG)
  365.  
  366. It's a manual process, but if you follow the instructions, it will take only a minute to do and the result will be a nice looking GUI. The steps you'll take are:
  367. 1. Sketch your GUI on paper
  368. 2. Divide your GUI up into rows
  369. 3. Label each Element with the Element name
  370. 4. Write your Python code using the labels as pseudo-code
  371.  
  372. Let's take a couple of examples.
  373.  
  374. **Enter a number**.... Popular beginner programs are often based on a game or logic puzzle that requires the user to enter something, like a number. The "high-low" answer game comes to mind where you try to guess the number based on high or low tips.
  375.  
  376. **Step 1- Sketch the GUI**
  377. ![gui1_1](https://user-images.githubusercontent.com/13696193/44160127-6a584900-a087-11e8-8fec-09099a8e16f6.JPG)
  378.  
  379. **Step 2 - Divide into rows**
  380.  
  381. ![gui2_1](https://user-images.githubusercontent.com/13696193/44160128-6a584900-a087-11e8-9973-af866fb94c56.JPG)
  382.  
  383. Step 3 - Label elements
  384.  
  385. ![gui6_1](https://user-images.githubusercontent.com/13696193/44160116-64626800-a087-11e8-8b57-671c0461b508.JPG)
  386.  
  387. Step 4 - Write the code
  388. The code we're writing is the layout of the GUI itself. This tutorial only focuses on getting the window code written, not the stuff to display it, get results.
  389.  
  390. We have only 1 element on the first row, some text. Rows are written as a "list of elements", so we'll need [ ] to make a list. Here's the code for row 1
  391.  
  392. ```
  393. [ sg.Text('Enter a number') ]
  394. ```
  395.  
  396. Row 2 has 1 elements, an input field.
  397.  
  398. ```
  399. [ sg.Input() ]
  400. ```
  401.  
  402. Row 3 has an OK button
  403.  
  404. ```
  405. [ sg.OK() ]
  406. ```
  407.  
  408. Now that we've got the 3 rows defined, they are put into a list that represents the entire window.
  409.  
  410. ```
  411. layout = [ [sg.Text('Enter a Number')],
  412. [sg.Input()],
  413. [sg.OK()] ]
  414. ```
  415.  
  416. Finally we can put it all together into a program that will display our window.
  417.  
  418. ```python
  419. import PySimpleGUI as sg
  420.  
  421. layout = [[sg.Text('Enter a Number')],
  422. [sg.Input()],
  423. [sg.OK()] ]
  424.  
  425. event, (number,) = sg.Window('Enter a number example', layout).Read()
  426.  
  427. sg.Popup(event, number)
  428. ```
  429.  
  430. ### Example 2 - Get a filename
  431. Let's say you've got a utility you've written that operates on some input file and you're ready to use a GUI to enter than filename rather than the command line. Follow the same steps as the previous example - draw your window on paper, break it up into rows, label the elements.
  432.  
  433. ![gui4_1](https://user-images.githubusercontent.com/13696193/44160132-6a584900-a087-11e8-862f-7d791a67ee5d.JPG)
  434. ![gui5_1](https://user-images.githubusercontent.com/13696193/44160133-6af0df80-a087-11e8-9dec-bb4d4c59393d.JPG)
  435.  
  436. Writing the code for this one is just as straightforward. There is one tricky thing, that browse for a file button. Thankfully PySimpleGUI takes care of associating it with the input field next to it. As a result, the code looks almost exactly like the window on the paper.
  437.  
  438. ```python
  439. import PySimpleGUI as sg
  440.  
  441. layout = [[sg.Text('Filename')],
  442. [sg.Input(), sg.FileBrowse()],
  443. [sg.OK(), sg.Cancel()] ]
  444.  
  445. event, (number,) = sg.Window('Get filename example', layout).Read()
  446.  
  447. sg.Popup(event, number)
  448. ```
  449.  
  450. Read on for detailed instructions on the calls that show the window and return your results.
  451.  
  452. # Copy these design patterns!
  453.  
  454. All of your PySimpleGUI programs will utilize one of these 2 design patterns depending on the type of window you're implementing.
  455.  
  456. ## Pattern 1 - "One-shot Window" - Read into list or dictionary (**The Most Common** Pattern)
  457.  
  458. This will be the most common pattern you'll follow if you are not using an "event loop" (not reading the window multiple times). The window is read and closes.
  459.  
  460. It's unusual to assign the values returned from the read call directly into user variables. Usually the variables are grouped together into a list or dictionary of multiple return values.
  461.  
  462. ```python
  463. import PySimpleGUI as sg
  464.  
  465. window_rows = [[sg.Text('SHA-1 and SHA-256 Hashes for the file')],
  466. [sg.InputText(), sg.FileBrowse()],
  467. [sg.Submit(), sg.Cancel()]]
  468.  
  469. window = sg.Window('SHA-1 & 256 Hash', window_rows)
  470.  
  471. event, values = window.Read()
  472. window.Close()
  473.  
  474. source_filename = values[0]
  475. ```
  476.  
  477. ## Pattern 2 A - Persistent window (multiple reads using an event loop)
  478.  
  479. Some of the more advanced programs operate with the window remaining visible on the screen. Input values are collected, but rather than closing the window, it is kept visible acting as a way to both output information to the user and gather input data.
  480.  
  481. This code will present a window and will print values until the user clicks the exit button or closes window using an X.
  482.  
  483. ```python
  484. import PySimpleGUI as sg
  485.  
  486. layout = [[sg.Text('Persistent window')],
  487. [sg.Input(do_not_clear=True)],
  488. [sg.Button('Read'), sg.Exit()]]
  489.  
  490. window = sg.Window('Window that stays open', layout)
  491.  
  492. while True:
  493. event, values = window.Read()
  494. if event is None or event == 'Exit':
  495. break
  496. print(event, values)
  497.  
  498. window.Close()
  499. ```
  500.  
  501. ## Pattern 2 B - Persistent window (multiple reads using an event loop + updates data in window)
  502.  
  503. This is a slightly more complex, but maybe more realistic version that reads input from the user and displays that input as text in the window. Your program is likely to be doing both of those activities so this will give you a big jump-start.
  504.  
  505. Do not worry yet what all of these statements mean. Just copy it so you can begin to play with it, make some changes. Experiment to see how thing work.
  506.  
  507. A final note... the parameter `do_not_clear` in the input call determines the action of the input field after a button event. If this value is True, the input value remains visible following button clicks. If False, then the input field is CLEARED of whatever was input. If you are building a "Form" type of window with data entry, you likely want False, the default setting (you can remove the parameter completely).
  508.  
  509. ```python
  510. import sys
  511. if sys.version_info[0] >= 3:
  512. import PySimpleGUI as sg
  513. else:
  514. import PySimpleGUI27 as sg
  515.  
  516. layout = [[sg.Text('Your typed chars appear here:'), sg.Text('', key='_OUTPUT_') ],
  517. [sg.Input(do_not_clear=True, key='_IN_')],
  518. [sg.Button('Show'), sg.Button('Exit')]]
  519.  
  520. window = sg.Window('Window Title', layout)
  521.  
  522. while True: # Event Loop
  523. event, values = window.Read()
  524. print(event, values)
  525. if event is None or event == 'Exit':
  526. break
  527. if event == 'Show':
  528. # change the "output" element to be the value of "input" element
  529. window.Element('_OUTPUT_').Update(values['_IN_'])
  530.  
  531. window.Close()
  532. ```
  533.  
  534.  
  535.  
  536. ## How GUI Programming in Python Should Look? At least for beginners ?
  537.  
  538. While one goal was making it simple to create a GUI another just as important goal was to do it in a Pythonic manner. Whether it achieved these goals is debatable, but it was an attempt just the same.
  539.  
  540. The key to custom windows in PySimpleGUI is to view windows as ROWS of GUI Elements. Each row is specified as a list of these Elements. Put the rows together and you've got a window. This means the GUI is defined as a series of Lists, a Pythonic way of looking at things.
  541.  
  542. Let's dissect this little program
  543. ```python
  544. import PySimpleGUI as sg
  545.  
  546. layout = [[sg.Text('Rename files or folders')],
  547. [sg.Text('Source for Folders', size=(15, 1)), sg.InputText(), sg.FolderBrowse()],
  548. [sg.Text('Source for Files ', size=(15, 1)), sg.InputText(), sg.FolderBrowse()],
  549. [sg.Submit(), sg.Cancel()]]
  550.  
  551. window = sg.Window('Rename Files or Folders', layout)
  552.  
  553. event, values = window.Read()
  554. ```
  555.  
  556.  
  557. ![snap0131](https://user-images.githubusercontent.com/13696193/43417007-df6d8408-9407-11e8-9986-30f0415f08a5.jpg)
  558.  
  559. Let's agree the window has 4 rows.
  560.  
  561. The first row only has **text** that reads `Rename files or folders`
  562.  
  563. The second row has 3 elements in it. First the **text** `Source for Folders`, then an **input** field, then a **browse** button.
  564.  
  565. Now let's look at how those 2 rows and the other two row from Python code:
  566.  
  567. ```python
  568. layout = [[sg.Text('Rename files or folders')],
  569. [sg.Text('Source for Folders', size=(15, 1)), sg.InputText(), sg.FolderBrowse()],
  570. [sg.Text('Source for Files ', size=(15, 1)), sg.InputText(), sg.FolderBrowse()],
  571. [sg.Submit(), sg.Cancel()]]
  572. ```
  573.  
  574. See how the source code mirrors the layout? You simply make lists for each row, then submit that table to PySimpleGUI to show and get values from.
  575.  
  576. And what about those return values? Most people simply want to show a window, get the input values and do something with them. So why break up the code into button callbacks, etc, when I simply want my window's input values to be given to me.
  577.  
  578. For return values the window is scanned from top to bottom, left to right. Each field that's an input field will occupy a spot in the return values.
  579.  
  580. In our example window, there are 2 fields, so the return values from this window will be a list with 2 values in it.
  581. ```python
  582. event, values = window.Read()
  583. folder_path, file_path = values
  584. ```
  585.  
  586. In one statement we both show the window and read the user's inputs. In the next the *list* of return values is split into individual variables `folder_path` and `file_path`.
  587.  
  588. Isn't this what a Python programmer looking for a GUI wants? Something easy to work with to get the values and move on to the rest of the program, where the real action is taking place. Why write pages of GUI code when the same layout can be achieved with PySimpleGUI in 3 or 4 lines of code. 4 lines or 40? Most would choose 4.
  589.  
  590.  
  591. ## Return values
  592.  
  593. As of version 2.8 there are 2 forms of return values, list and dictionary.
  594.  
  595. ### Two Return Values
  596.  
  597. All Window Read calls return 2 values. By convention a read statement is written:
  598. ```python
  599. event, values = window.Read()
  600. ```
  601.  
  602. You don't HAVE to write your reads in this way. You can name your variables however you want. But if you want to code them in a way that other programmers using PySimpleGUI are used to, then use these statements.
  603.  
  604. ## Events
  605.  
  606. The first parameter `event` describes **why** the read completed. Events are one of these:
  607.  
  608. For all Windows:
  609.  
  610. * Button click
  611. * Window closed using X
  612.  
  613. For Windows that have specifically enabled these. Please see the appropriate section in this document to learn about how to enable these and what the event return values are.
  614.  
  615. * Keyboard key press
  616. * Mouse wheel up/down
  617. * Menu item selected
  618. * An Element Changed (slider, spinner, etc)
  619. * A list item was clicked
  620. * Return key was pressed in input element
  621. * Timeout waiting for event
  622. * Text was clicked
  623. * Combobox item chosen
  624. * Table row selected
  625. * etc
  626.  
  627. ***Most*** of the time the event will be a button click or the window was closed.
  628.  
  629. ### Window closed event
  630.  
  631. Another convention to follow is the check for windows being closed with an X. This is an important event to catch. If you don't check for this and you attempt to use the window, your program will crash. Please check for closed window and exit your program gracefully.
  632.  
  633. To check for a closed window use this line of code:
  634.  
  635. ```python
  636. if event is None:
  637. ```
  638.  
  639. Putting it all together we end up with an "event loop" that looks something like this:
  640. ```python
  641. while True:
  642. event, values = window.Read()
  643. if event is None:
  644. break
  645. ```
  646. ### Button Click Events
  647.  
  648. By default buttons will always return a click event, or in the case of realtime buttons, a button down event. You don't have to do anything to enable button clicks. To disable the events, disable the button using its Update method.
  649.  
  650. You can enable an additional "Button Modified" event by setting `enable_events=True` in the Button call. These events are triggered when something 'writes' to a button, ***usually*** it's because the button is listed as a "target" in another button.
  651.  
  652. The button value from a Read call will be one of 2 values:
  653. 1. The Button's text - Default
  654. 2. The Button's key - If a key is specified
  655.  
  656. If a button has a key set when it was created, then that key will be returned. If no key is set, then the button text is returned. If no button was clicked, but the window returned anyway, the event value is None.
  657.  
  658. ### **None is returned when the user clicks the X to close a window.**
  659.  
  660. If your window has an event loop where it is read over and over, remember to give your user an "out". You should ***always check for a None value*** and it's a good practice to provide an Exit button of some kind. Thus design patterns often resemble this Event Loop:
  661.  
  662. ```python
  663. while True:
  664. event, values = window.Read()
  665. if event is None or event == 'Quit':
  666. break
  667. ```
  668.  
  669.  
  670. ### Element Events
  671.  
  672. Some elements are capable of generating events when something happens to them. For example, when a slider is moved, or list item clicked on or table row clicked on. These events are not enabled by default. To enable events for an Element, set the parameter `enable_events=True`. This is the same as the older `click_submits` parameter. You will find the `click_submits` parameter still in the function definition. You can continue to use it. They are the same setting. An 'or' of the two values is used. In the future, click_submits will be removed so please migrate your code to using `enable_events`.
  673.  
  674.  
  675. | name | events |
  676. | - | - |
  677. | InputText | any change |
  678. | Combo | item chosen |
  679. | Option menu | item chosen |
  680. | Listbox | selection changed |
  681. | Radio | selection changed |
  682. | Checkbox | selection changed |
  683. | Spinner | new item selected |
  684. | Multiline | any change |
  685. | Text | clicked |
  686. | Status Bar | clicked |
  687. | Graph | clicked |
  688. | TabGroup | tab clicked |
  689. | Slider | slider moved |
  690. | Table | row selected |
  691. | Tree | node selected |
  692. | ButtonMenu | menu item chosen |
  693. | Right click menu | menu item chosen |
  694.  
  695. ### Other Events
  696.  
  697. #### Menubar menu item chosen for MenuBar menus and ButtonMenu menus
  698.  
  699. You will receive the key for the MenuBar and ButtonMenu. Use that key to read the value in the return values dictionary. The value shown will be the full text plus key for the menu item chosen. Remember that you can put keys onto menu items. You will get the text and the key together as you defined it in the menu
  700. definition.
  701.  
  702. #### Right Click menu item chosen
  703.  
  704. Unlike menu bar and button menus, you will directly receive the menu item text and its key value. You will not do a dictionary lookup to get the value. It is the event code returned from WindowRead().
  705.  
  706.  
  707. #### Windows - keyboard, mouse scroll wheel
  708.  
  709. Windows are capable of returning keyboard events. These are returned as either a single character or a string if it's a special key. Experiment is all I can say. The mouse scroll wheel events are also strings. Put a print in your code to see what's returned.
  710.  
  711. #### Timeouts
  712.  
  713. If you set a timeout parameter in your read, then the system TIMEOUT_KEY will be returned. If you specified your own timeout key in the Read call then that value will be what's returned instead.
  714.  
  715. ### The `values` Variable - Return values as a list
  716.  
  717. The second parameter from a Read call is either a list or a dictionary of the input fields on the Window.
  718.  
  719. By default return values are a list of values, one entry for each input field.
  720.  
  721. Each of the Elements that are Input Elements will have a value in the list of return values. You can unpack your GUI directly into the variables you want to use.
  722.  
  723. event, (filename, folder1, folder2, should_overwrite) = sg.Window('My title', window_rows).Read()
  724.  
  725. Or, more commonly, you can unpack the return results separately.
  726.  
  727. ```python
  728. event, values = sg.Window('My title', window_rows).Read()
  729. event, value_list = window.Read()
  730. value1 = value_list[0]
  731. value2 = value_list[1]
  732. ...
  733. ```
  734. However, this method isn't good when you have a lot of input fields. If you insert a new element into your window then you will have to shuffle your unpacks down, modifying each of the statements to reference `value_list[x] `.
  735.  
  736. The more common / advanced method is to request your values be returned as a dictionary.
  737.  
  738. ### `values` Variable - Return values as a dictionary
  739.  
  740. For those of you that have not encountered a Python dictionary, don't freak out! Just copy and paste the sample code and modify it. Follow this design pattern and you'll be fine. And you might learn something along the way.
  741.  
  742. For windows longer than 3 or 4 fields you will want to use a dictionary to help you organize your return values. In almost all (if not all) of the demo programs you'll find the return values being passed as a dictionary. It is not a difficult concept to grasp, the syntax is easy to understand, and it makes for very readable code.
  743.  
  744. The most common window read statement you'll encounter looks something like this:
  745.  
  746. `window = sg.Window("My title", layout).Read()`
  747.  
  748. To use a dictionary, you will need to:
  749. * Mark each input element you wish to be in the dictionary with the keyword `key`.
  750.  
  751. If **any** element in the window has a `key`, then **all** of the return values are returned via a dictionary. If some elements do not have a key, then they are numbered starting at zero.
  752.  
  753. Let's take a look at your first dictionary-based window.
  754.  
  755. ```python
  756. import PySimpleGUI as sg
  757.  
  758. layout = [
  759. [sg.Text('Please enter your Name, Address, Phone')],
  760. [sg.Text('Name', size=(15, 1)), sg.InputText('1', key='_name_')],
  761. [sg.Text('Address', size=(15, 1)), sg.InputText('2', key='_address_')],
  762. [sg.Text('Phone', size=(15, 1)), sg.InputText('3', key='_phone_')],
  763. [sg.Submit(), sg.Cancel()]
  764. ]
  765.  
  766. window = sg.Window('Simple data entry window', layout)
  767. event, values = window.Read()
  768.  
  769. sg.Popup(event, values, values['_name_'], values['_address_'], values['_phone_'])
  770. ```
  771.  
  772. To get the value of an input field, you use whatever value used as the `key` value as the index value. Thus to get the value of the name field, it is written as
  773.  
  774. values['name']
  775.  
  776. Think of the variable values in the same way as you would a list, however, instead of using 0,1,2, to reference each item in the list, use the values of the key. The Name field in the window above is referenced by `values['_name_']`.
  777.  
  778. You will find the key field used quite heavily in most PySimpleGUI windows unless the window is very simple.
  779.  
  780. Another convention you'll see in some of the demo programs is keys being named with an underscore at the beginning and the end. You don't HAVE to do this... your key value may look like this:
  781. `key = 'name'`
  782.  
  783. The reason for this naming convention is that when you are scanning the code, these key values jump out at you. You instantly know it's a key. Try scanning the code above and see if those keys pop out.
  784. `key = '_name_'`
  785.  
  786.  
  787.  
  788. ## The Event Loop / Callback Functions
  789.  
  790. All GUIs have one thing in common, an "event loop". Usually the GUI framework runs the event loop for you, but sometimes you want greater control and will run your own event loop. You often hear the term event loop when discussing embedded systems or on a Raspberry Pi.
  791.  
  792. With PySimpleGUI if your window will remain open following button clicks, then your code will have an event loop. If your program shows a single "one-shot" window, collects the data and then has no other GUI interaction, then you don't need an event loop.
  793.  
  794. There's nothing mysterious about event loops... they are loops where you take care of.... wait for it..... *events*. Events are things like button clicks, key strokes, mouse scroll-wheel up/down.
  795.  
  796. Let's take a Pi demo program as an example. This program shows a GUI window, gets button presses, and uses them to control some LEDs. It loops, reading user input and doing something with it.
  797.  
  798. This little program has a typical Event Loop
  799.  
  800. ![readme example](https://user-images.githubusercontent.com/13696193/46566965-f4d65f80-c8f6-11e8-91a3-8cebad0cba90.jpg)
  801.  
  802. ```python
  803. import PySimpleGUI as sg
  804.  
  805. layout = [[sg.Text('Click read to read the input value')],
  806. [sg.Input()],
  807. [sg.RButton('Read'), sg.Exit()]]
  808.  
  809. window = sg.Window('Persistent GUI Window', layout)
  810.  
  811. while True:
  812. event, values = window.Read()
  813. if event is None or event == 'Exit':
  814. break
  815. print(event, values)
  816. window.Close()
  817. ```
  818.  
  819. In the Event Loop we are reading the window and then doing a series of button compares to determine what to do based on the button that was clicks (value of `button` variable)
  820.  
  821. The way buttons are presented to the caller in PySimpleGUI is ***not*** how *most* GUI frameworks handle button clicks. Most GUI frameworks, including tkinter, use ***callback*** functions, a function you define would be called when a button is clicked. This requires you to write asynchronous code, a concept beginners often stumble on and one that presents a barrier.
  822.  
  823. There is a more communications that have to happen between parts of your program when using callbacks. Callbacks break apart your program's logic apart and scatter it. One of the larger hurdles for beginners to GUI programming are these callback functions.
  824.  
  825. PySimpleGUI was specifically designed in a way so that callbacks would not be required. There is no coordination between one function and another required. You simply read your button click and take appropriate action at the same location in the code as when you read the button value.
  826.  
  827. Whether or not this is a "proper" design for GUI programs can be debated. It's not a terrible trade-off to run your own event loop and having a functioning GUI application versus one that maybe never gets written because callback functions were too much to grasp.
  828.  
  829.  
  830. ## All Widgets / Elements
  831.  
  832. This code utilizes many of the common Elements. It does not include Tabs/Tab Groups.
  833. ```python
  834. import PySimpleGUI as sg
  835.  
  836. sg.ChangeLookAndFeel('GreenTan')
  837.  
  838. # ------ Menu Definition ------ #
  839. menu_def = [['File', ['Open', 'Save', 'Exit', 'Properties']],
  840. ['Edit', ['Paste', ['Special', 'Normal', ], 'Undo'], ],
  841. ['Help', 'About...'], ]
  842.  
  843. # ------ Column Definition ------ #
  844. column1 = [[sg.Text('Column 1', background_color='#F7F3EC', justification='center', size=(10, 1))],
  845. [sg.Spin(values=('Spin Box 1', '2', '3'), initial_value='Spin Box 1')],
  846. [sg.Spin(values=('Spin Box 1', '2', '3'), initial_value='Spin Box 2')],
  847. [sg.Spin(values=('Spin Box 1', '2', '3'), initial_value='Spin Box 3')]]
  848.  
  849. layout = [
  850. [sg.Menu(menu_def, tearoff=True)],
  851. [sg.Text('All graphic widgets in one window!', size=(30, 1), justification='center', font=("Helvetica", 25), relief=sg.RELIEF_RIDGE)],
  852. [sg.Text('Here is some text.... and a place to enter text')],
  853. [sg.InputText('This is my text')],
  854. [sg.Frame(layout=[
  855. [sg.Checkbox('Checkbox', size=(10,1)), sg.Checkbox('My second checkbox!', default=True)],
  856. [sg.Radio('My first Radio! ', "RADIO1", default=True, size=(10,1)), sg.Radio('My second Radio!', "RADIO1")]], title='Options',title_color='red', relief=sg.RELIEF_SUNKEN, tooltip='Use these to set flags')],
  857. [sg.Multiline(default_text='This is the default Text should you decide not to type anything', size=(35, 3)),
  858. sg.Multiline(default_text='A second multi-line', size=(35, 3))],
  859. [sg.InputCombo(('Combobox 1', 'Combobox 2'), size=(20, 1)),
  860. sg.Slider(range=(1, 100), orientation='h', size=(34, 20), default_value=85)],
  861. [sg.InputOptionMenu(('Menu Option 1', 'Menu Option 2', 'Menu Option 3'))],
  862. [sg.Listbox(values=('Listbox 1', 'Listbox 2', 'Listbox 3'), size=(30, 3)),
  863. sg.Frame('Labelled Group',[[
  864. sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=25),
  865. sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=75),
  866. sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=10),
  867. sg.Column(column1, background_color='#F7F3EC')]])],
  868. [sg.Text('_' * 80)],
  869. [sg.Text('Choose A Folder', size=(35, 1))],
  870. [sg.Text('Your Folder', size=(15, 1), auto_size_text=False, justification='right'),
  871. sg.InputText('Default Folder'), sg.FolderBrowse()],
  872. [sg.Submit(tooltip='Click to submit this window'), sg.Cancel()]
  873. ]
  874.  
  875.  
  876. window = sg.Window('Everything bagel', layout, default_element_size=(40, 1), grab_anywhere=False)
  877.  
  878. event, values = window.Read()
  879.  
  880. sg.Popup('Title',
  881. 'The results of the window.',
  882. 'The button clicked was "{}"'.format(event),
  883. 'The values are', values)
  884. ```
  885. This is a somewhat complex window with quite a bit of custom sizing to make things line up well. This is code you only have to write once. When looking at the code, remember that what you're seeing is a list of lists. Each row contains a list of Graphical Elements that are used to create the window.
  886.  
  887. ![everything bagel](https://user-images.githubusercontent.com/13696193/45914128-87163800-be0e-11e8-9a83-7ee5960e88b9.jpg)
  888.  
  889. Clicking the Submit button caused the window call to return. The call to Popup resulted in this window.
  890.  
  891. ![everything bagel reseults](https://user-images.githubusercontent.com/13696193/45914129-87aece80-be0e-11e8-8aae-9a483a9ad4a6.jpg)
  892.  
  893.  
  894. **`Note, button value can be None`**. The value for `button` will be the text that is displayed on the button element when it was created. If the user closed the window using something other than a button, then `button` will be `None`. It is ***vitally*** ***important*** that your code contain the proper checks for None. Always give your users a way out of the window. Otherwise you'll end up with windows that never properly close.
  895.  
  896. You can see in the results Popup window that the values returned are a list. Each input field in the window generates one item in the return values list. All input fields return a `string` except for Check Boxes and Radio Buttons. These return `bool`.
  897.  
  898. # Building Custom Windows
  899.  
  900. You will find it ***much easier*** to write code using PySimpleGUI if you use an IDE such as PyCharm. The features that show you documentation about the API call you are making will help you determine which settings you want to change, if any. In PyCharm, two commands are particularly helpful.
  901.  
  902. Control-Q (when cursor is on function name) brings up a box with the function definition
  903. Control-P (when cursor inside function call "()") shows a list of parameters and their default values
  904.  
  905. ## Synchronous windows
  906. The most common use of PySimpleGUI is to display and collect information from the user. The most straightforward way to do this is using a "blocking" GUI call. Execution is "blocked" while waiting for the user to close the GUI window/dialog box.
  907. You've already seen a number of examples above that use blocking windows. A truly non-blocking Read call looks like this:
  908.  
  909. ```python
  910. event, values = window.Read(timeout=0)
  911. ```
  912.  
  913. You can learn more about these async / non-blocking windows toward the end of this document.
  914.  
  915. # Window Object - Beginning a window
  916. The first step is to create the window object using the desired window customization.
  917.  
  918. This is the definition of the Window object:
  919.  
  920. ```python
  921. Window( title,
  922. default_element_size=DEFAULT_ELEMENT_SIZE,
  923. default_button_element_size=(None,None),
  924. auto_size_text=None,
  925. auto_size_buttons=None,
  926. location=(None,None),
  927. size=(None,None),
  928. element_padding=None,
  929. button_color=None,
  930. font=None,
  931. progress_bar_color=(None,None),
  932. background_color=None,
  933. border_depth=None,
  934. auto_close=False,
  935. auto_close_duration=DEFAULT_AUTOCLOSE_TIME,
  936. icon=DEFAULT_WINDOW_ICON,
  937. force_toplevel=False,
  938. alpha_channel=1,
  939. return_keyboard_events=False,
  940. use_default_focus=True,
  941. text_justification=None,
  942. no_titlebar=False,
  943. grab_anywhere=False,
  944. keep_on_top=False,
  945. resizable=False,
  946. disable_close=False,
  947. disable_minimize=False,
  948. right_click_menu=None):
  949. ```
  950.  
  951. Parameter Descriptions. You will find these same parameters specified for each `Element` and some of them in `Row` specifications. The `Element` specified value will take precedence over the `Row` and `window` values.
  952.  
  953. | Name | Meaning |
  954. | - | - |
  955. | default_element_size | Size of elements in window in characters (width, height) |
  956. | default_button_element_size | Size of buttons on this window |
  957. | auto_size_text | Bool. True if elements should size themselves according to contents. Defaults to True |
  958. | auto_size_buttons | Bool. True if button elements should size themselves according to their text label |
  959. | location | (x,y) Location to place window in pixels |
  960. | size | (w,h) forces a window to be a paricular size|
  961. | element_padding | (w,h) default padding amount for elements|
  962. | font | Font name and size for elements of the window |
  963. | button_color | Default color for buttons (foreground, background). Can be text or hex |
  964. | progress_bar_color | Foreground and background colors for progress bars |
  965. | background_color | Color of the window background |
  966. | border_depth | Amount of 'bezel' to put on input boxes, buttons, etc. |
  967. | auto_close | Bool. If True window will autoclose |
  968. | auto_close_duration | Duration in seconds before window closes |
  969. | icon | .ICO file that will appear on the Task Bar and end of Title Bar |
  970. | force_top_level | Bool. If set causes a tk.Tk window to be used as primary window rather than tk.TopLevel. Used to get around Matplotlib problem |
  971. | alpha_channel | Float 0 to 1. 0 is invisible, 1 is fully visible, Anything between will be semi-transparent |
  972. | return_keyboard_events | if True key presses are returned as buttons |
  973. | use_default_focus | if True and no focus set, then automatically set a focus |
  974. | text_justification | Justification to use for Text Elements in this window |
  975. | no_titlebar | Create window without a titlebar |
  976. | grab_anywhere | Grab any location on the window to move the window |
  977. | keep_on_top | if True then window will always stop on top of other windows on the screen. Great for floating toolbars. |
  978. | resizable | if True | user can manually changge the wize of the window. Defaults to False|
  979. | disable_close | if True user will not be able to close using the X. |
  980. | disable_minimize | if True user will not be able to minimize the window|
  981. | right_click_menu | menu definition that will be used on wall elements that support right click. If a definition is specified on an element then it will be used instead.|
  982. | | |
  983.  
  984.  
  985. ### Window Location
  986. PySimpleGUI computes the exact center of your window and centers the window on the screen. If you want to locate your window elsewhere, such as the system default of (0,0), if you have 2 ways of doing this. The first is when the window is created. Use the `location` parameter to set where the window. The second way of doing this is to use the `SetOptions` call which will set the default window location for all windows in the future.
  987.  
  988. ### Window Size
  989.  
  990. You can get your window's size by access the `Size`property. The window has to be Read once or Finalized in order for the value to be correct. Note that it's a property, not a call.
  991.  
  992. `my_windows_size = window.Size`
  993.  
  994. To finalize your window:
  995.  
  996. ```pytyhon
  997. window = Window('My Title', layout).Finalize()
  998. ```
  999.  
  1000.  
  1001. ### Element Sizes
  1002. Note several variables that deal with "size". Element sizes are measured in characters. A Text Element with a size of 20,1 has a size of 20 characters wide by 1 character tall.
  1003.  
  1004. The default Element size for PySimpleGUI is `(45,1)`.
  1005.  
  1006. Sizes can be set at the element level, or in this case, the size variables apply to all elements in the window. Setting `size=(20,1)` in the window creation call will set all elements in the window to that size.
  1007.  
  1008. There are a couple of widgets where one of the size values is in pixels rather than characters. This is true for Progress Meters and Sliders. The second parameter is the 'height' in pixels.
  1009.  
  1010. ### No Titlebar
  1011.  
  1012. Should you wish to create cool looking windows that are clean with no windows titlebar, use the no_titlebar option when creating the window.
  1013.  
  1014. Be sure an provide your user an "exit" button or they will not be able to close the window! When no titlebar is enabled, there will be no icon on your taskbar for the window. Without an exit button you will need to kill via taskmanager... not fun.
  1015.  
  1016. Windows with no titlebar rely on the grab anywhere option to be enabled or else you will be unable to move the window.
  1017.  
  1018. Windows without a titlebar can be used to easily create a floating launcher.
  1019.  
  1020. Linux users! Note that this setting has side effects for some of the other Elements. Multi-line input doesn't work at all, for example So, use with caution.
  1021.  
  1022.  
  1023. ![floating launcher](https://user-images.githubusercontent.com/13696193/45258246-71bafb80-b382-11e8-9f5e-79421e6c00bb.jpg)
  1024.  
  1025.  
  1026. ### Grab Anywhere
  1027.  
  1028. This is a feature unique to PySimpleGUI.
  1029.  
  1030. Note - there is a warning message printed out if the user closes a non-blocking window using a button with grab_anywhere enabled. There is no harm in these messages, but it may be distressing to the user. Should you wish to enable for a non-blocking window, simply get grab_anywhere = True when you create the window.
  1031.  
  1032. ### Always on top
  1033.  
  1034. To keep a window on top of all other windows on the screen, set keep_on_top = True when the window is created. This feature makes for floating toolbars that are very helpful and always visible on your desktop.
  1035.  
  1036. ### Focus
  1037.  
  1038. PySimpleGUI will set a default focus location for you. This generally means the first input field. You can set the focus to a particular element. If you are going to set the focus yourself, then you should turn off the automatic focus by setting `use_default_focus=False` in your Window call.
  1039.  
  1040.  
  1041. ### Window Methods (things you can do with a Window object)
  1042.  
  1043. There are a few methods (functions) that you will see in this document that act on Windows. The ones you will primarily be calling are:
  1044.  
  1045. window.Layout(layout) - Recommend moving away from this nethod and using layout parameter instead. Turns your definition of the Window into Window
  1046. window.Finalize() - creates the tkinter objects for the Window. Normally you do not call this
  1047. window.Read() - Read the Windows values and get the button / key that caused the Read to return. Can have an optional timeout
  1048. window.ReadNonBlocking() - NO LONGER USED!
  1049. window.Refresh() - Use if updating elements and want to show the updates prior to the nex Read
  1050. window.Fill(values_dict) - Fill each Element with entry from the dictionary passed in
  1051. window.SaveToDisk(filename) - Save the Window's values to disk
  1052. window.LoadFromDisk(filename) - Load the Window's values from disk
  1053. window.Close() - To close your window, if a button hasn't already closed it
  1054. window.Disable() - Use to disable the window inputwhen opening another window on top of the primnary Window
  1055. window.Enable() - Re-enable a Disabled window
  1056. window.FindElement(key, silent_on_error=False) - Returns the element that has a matching key value
  1057. window.Element(key, silent_on_error=False) - EXACTLY the same as calling FindElement
  1058. window.Move(x,y) - Moves window to location x,y on screen'
  1059. window.SetAlpha(alpha) - Changes window transparency
  1060. window.BringToFront() - Brings the window to the top of other windows on the screen
  1061. window.Disappear(), Reappear() - Uses alpha channel to make window disappear
  1062. window.Hide(), UnHide() - Hides a window
  1063. window.CurrentLocation() - Returns current window location
  1064. window.Size = w,h - Forces a window to be a particular size. Note this is a property not a method
  1065. window.Size - Tuple (w,h)The size of the current window. Note this is a property
  1066. window.Minimize() - Minimizes window to taskbar
  1067.  
  1068. ## Window Methods
  1069.  
  1070. There are a number of operations you can do on a window after you've created the window. You call these after creating your Windows object.
  1071.  
  1072. #### Layout(rows)
  1073.  
  1074. Call to set the window layout. Must be called prior to Read. Most likely "chained" in line with the Window creation.
  1075.  
  1076. ```python
  1077. window = sg.Window('My window title', layout)
  1078. ```
  1079.  
  1080. #### Finalize()
  1081.  
  1082. Call to force a window to go through the final stages of initialization. This will cause the tkinter resources to be allocated so that they can then be modified. This also causes your window to appear. If you do not want your window to appear when Finalize is called, then set the Alpha to 0 in your window's creation parameters.
  1083.  
  1084. If you want to call an element's Update method or call a Graph element's drawing primitives, you ***must*** either call `Read` or `Finalize` prior to making those calls.
  1085.  
  1086.  
  1087. #### Read(timeout=None, timeout_key='__TIMEOUT_ _ ')
  1088.  
  1089. Read the Window's input values and button clicks in a blocking-fashion
  1090.  
  1091. Returns event, values. Adding a timeout can be achieved by setting timeout=number of milliseconds before the Read times out after which a "timeout event" is returned. The value of timeout_key will be returned as the event. If you do not specify a timeout key, then the value `TIMEOUT_KEY` will be returned.
  1092.  
  1093. If you set the timeout = 0, then the Read will immediately return rather than waiting for input or for a timeout. This is the same as the old ReadNonBlocking call.
  1094.  
  1095. #### ReadNonBlocking() (NO LONGER USED)
  1096.  
  1097. While this call will technically still work, it is being removed. If you want to get the same result, call Read with timeout = 0.
  1098.  
  1099. Read the Window's input values and button clicks but without blocking. It will immediately return. **Consider using Read with non-zero timeout instead!**
  1100.  
  1101. Will consume 100% of your CPU if you do not have other blocking calls in your event loop.
  1102.  
  1103. |name|meaning|
  1104. |-|-|
  1105. | `Refresh() ` | Cause changes to the window to be displayed on the screen. Normally not needed unless the changes are immediately required or if it's going to be a while before another call to Read. |
  1106. | `SetIcon(icon, pngbase64) ` | Sets the window's icon that will be shown on the titlebar. Can either be a filename or a base64 string.|
  1107. | `Fill(values_dict) ` | Populates the windows fields with the values shown in the dictionary.|
  1108. | `FindElementWithFocus() ` | Returns the Element that currently has the focus. Returns None if no Elements were found.|
  1109. | `SaveToDisk(filename) ` | Saves the window's values to disk |
  1110. | `LoadFromDisk(filename) ` | Fills in a window's fields based on previously saved file |
  1111. | `GetScreenDimensions() ` | Returns the size (w,h) of the screen in pixels |
  1112. | `CurrentLocation() ` | Returns current screen position (x,y) |
  1113. | `Move(x, y) ` | Move window to (x,y) position on the screen |
  1114. | `Minimize() ` | Sends the window to the taskbar |
  1115. | `Close() ` | Closes a window, blocking or non-blocking|
  1116. | `Disable() ` | Stops a window from responding until Enable is called|
  1117. | `Enable() ` | Re-enables a previously disabled window|
  1118. | `Hide() ` | Completely hides a window, including removing from the taskbar|
  1119. | `UnHide() ` | Restores a window hidden using Hide|
  1120. | `Disappear() ` | Makes a window disappear while leaving the icon on the taskbar|
  1121. | `Reappear() ` | Makes a window reappear that was previously made to disappear using Disappear()|
  1122. | `SetAlpha(alpha)` | Sets the window's transparency. 0 is completely transparent. 1 is fully visible, normal . Can also use the property Window.AlphaChannel instead of method function call|
  1123. | CloseNonBlocking()<br>(NO LONGER USED.<br> use Close instead) | Closes a non-blocking window |
  1124. | FindElement(key, silent_on_error=False) (shorthand version <br> Element) | Returns the Element that has a matching key. If the key is not found, an Error Element is returned so that the program will not crash should the user try to perform an "update". A Popup message will be shown |
  1125. |||
  1126.  
  1127.  
  1128. # Elements
  1129. "Elements" are the building blocks used to create windows. Some GUI APIs use the term "Widget" to describe these graphic elements.
  1130.  
  1131. - Text
  1132. - Single Line Input
  1133. - Buttons including these types:
  1134. - File Browse
  1135. - Folder Browse
  1136. - Calendar picker
  1137. - Date Chooser
  1138. - Read window
  1139. - Close window ("Button" & all shortcut buttons)
  1140. - Realtime
  1141. - Checkboxes
  1142. - Radio Buttons
  1143. - Listbox
  1144. - Slider
  1145. - Multi-line Text Input/Output
  1146. - Multi-line Text Output (Qt only)
  1147. - Scroll-able Output
  1148. - Vertical Separator
  1149. - Progress Bar
  1150. - Option Menu
  1151. - Menu
  1152. - ButtonMenu
  1153. - Frame
  1154. - Column
  1155. - Graph
  1156. - Image
  1157. - Table
  1158. - Tree
  1159. - Tab, TabGroup
  1160. - StatusBar
  1161. - Pane
  1162. - Stretch (Qt only)
  1163.  
  1164. ## Common Element Parameters
  1165. Some parameters that you will see on almost all Elements are:
  1166. - key - Used with window.FindElement and with return values
  1167. - tooltip - Hover your mouse over the elemnt and you'll get a popup with this text
  1168. - size - (width, height) - usually measured in characters-wide, rows-high. Sometimes they mean pixels
  1169. - font - specifies the font family, size, etc
  1170. - colors - Color name or #RRGGBB string
  1171. - pad - Amount of padding to put around element
  1172. - enable_events - Turns on the element specific events
  1173.  
  1174. #### Tooltip
  1175. Tooltips are text boxes that popup next to an element if you hold your mouse over the top of it. If you want to be extra kind to your window's user, then you can create tooltips for them by setting the parameter `tooltip` to some text string. You will need to supply your own line breaks / text wrapping. If you don't want to manually add them, then take a look at the standard library package `textwrap`.
  1176.  
  1177. Tooltips are one of those "polish" items that really dress-up a GUI and show's a level of sophistication. Go ahead, impress people, throw some tooltips into your GUI.
  1178.  
  1179. #### Size
  1180. Specifies the amount of room reserved for the Element. For elements that are character based, such a Text, it is (# characters, # rows). Sometimes it is a pixel measurement such as the Image element. And sometimes a mix like on the Slider element (characters long by pixels wide).
  1181.  
  1182. #### Colors
  1183. A string representing color. Anytime colors are involved, you can specify the tkinter color name such as 'lightblue' or an RGB hex value '#RRGGBB'. For buttons, the color parameter is a tuple (text color, background color)
  1184.  
  1185. #### Pad
  1186. The amount of room around the element in pixels. The default value is (5,3) which means leave 5 pixels on each side of the x-axis and 3 pixels on each side of the y-axis. You can change this on a global basis using a call to SetOptions, or on an element basis.
  1187.  
  1188. If you want more pixels on one side than the other, then you can split the number into 2 number. If you want 200 pixels on the left side, and 3 pixels on the right, the pad would be ((200,3), 3). In this example, only the x-axis is split.
  1189.  
  1190. #### Font
  1191. Specifies the font family, size, and style. Font families on Windows include:
  1192. * Arial
  1193. * Courier
  1194. * Comic,
  1195. * Fixedsys
  1196. * Times
  1197. * Verdana
  1198. * Helvetica (the default I think)
  1199.  
  1200. The fonts will vary from system to system, however, Tk 8.0 automatically maps Courier, Helvetica and Times to their corresponding native family names on all platforms. Also, font families cannot cause a font specification to fail on Tk 8.0 and greater.
  1201.  
  1202. If you wish to leave the font family set to the default, you can put anything not a font name as the family. The PySimpleGUI Demo programs and documentation use the family 'Any' to demonstrate this fact.. You could use "default" if that's more clear to you.
  1203.  
  1204. There are 2 formats that can be used to specify a font... a string, and a tuple
  1205. Tuple - (family, size, styles)
  1206. String - "Family Size Styles"
  1207.  
  1208. To specify an underlined, Helvetica font with a size of 15 the values:
  1209. ('Helvetica', 15, 'underline italics')
  1210. 'Helvetica 15 underline italics'
  1211.  
  1212. #### Key
  1213.  
  1214. If you are going to do anything beyond the basic stuff with your GUI, then you need to understand keys.
  1215. Keys are a way for you to "tag" an Element with a value that will be used to identify that element. After you put a key in an element's definition, the values returned from Read will use that key to tell you the value. For example, if you have an input field:
  1216. `Input(key='mykey')`
  1217.  
  1218. And your read looks like this: `event, values = Read()`
  1219.  
  1220. Then to get the input value from the read it would be: `values['mykey']`
  1221.  
  1222. You also use the same key if you want to call Update on an element. Please see the section below on Updates to understand that usage.
  1223.  
  1224. #### Visible
  1225. Beginning in version 3.17 you can create Elements that are initially invisible that you can later make visible.
  1226.  
  1227. To create an invisible Element, place the element in the layout like you normally would and add the parameter `visible=False`.
  1228.  
  1229. Later when you want to make that Element visible you simply call the Element's `Update` method and pass in the parameter `visible=True`
  1230.  
  1231. This feature works best on Qt, but does work on the tkinter version as well. The visible parameter can also be used with the Column and Frame "container" Elements.
  1232.  
  1233.  
  1234. ### Output Elements
  1235. Building a window is simply making lists of Elements. Each list is a row in the overall GUI dialog box. The definition looks something like this:
  1236.  
  1237. ```
  1238. layout = [ [row 1 element, row 1 element],
  1239. [row 2 element, row 2 element, row 2 element] ]
  1240. ```
  1241. The code is a crude representation of the GUI, laid out in text.
  1242. ## Shortcut Functions / Multiple Function Names
  1243.  
  1244. Many of the main method calls and Element names have shortcuts. This enables you to code much quicker once you are used to using the SDK. The Text Element, for example, has 3 different names `Text`, `Txt` or`T`. InputText can also be written `Input` or `In` . `FindElement` was recently renamed to `Element` because it's a commonly used function.
  1245.  
  1246.  
  1247. <!-- %!% -->
  1248. ## Text Element
  1249. ```
  1250. layout = [[sg.Text('This is what a Text Element looks like')]]
  1251. ```
  1252.  
  1253. ![simple text](https://user-images.githubusercontent.com/13696193/44959877-e9d97b00-aec3-11e8-9d24-b4405ee4a148.jpg)
  1254.  
  1255.  
  1256. The most basic element is the Text element. It simply displays text. Many of the 'options' that can be set for a Text element are shared by other elements.
  1257.  
  1258.  
  1259. <!-- <+Text+> -->
  1260.  
  1261. <!--
  1262. ```python
  1263. Text(text,
  1264. size=(None, None),
  1265. auto_size_text=None,
  1266. click_submits=False,
  1267. enable_events=False,
  1268. relief=None,
  1269. font=None,
  1270. text_color=None,
  1271. background_color=None,
  1272. justification=None,
  1273. pad=None,
  1274. key=None,
  1275. right_click_menu=None,
  1276. tooltip=None,
  1277. visible=True)
  1278. ```
  1279.  
  1280. Text - The text that's displayed
  1281. size - Element's size
  1282. click_submits - if clicked will cause a read call to return the key value of the button
  1283. enable_events - same as click_submits
  1284. relief - relief to use around the text
  1285. auto_size_text - Bool. Change width to match size of text
  1286. font - Font name and size to use
  1287. text_color - text color
  1288. background_color - background color
  1289. justification - Justification for the text. String - 'left', 'right', 'center'
  1290. pad - (x,y) amount of padding in pixels to use around element when packing
  1291. key - used to identify element. This value will return as button if click_submits True
  1292. right_click_menu - menu definition to display if right clicked
  1293. tooltip - string representing tooltip
  1294. -->
  1295.  
  1296. Some commonly used elements have 'shorthand' versions of the functions to make the code more compact. The functions `T` and `Txt` are the same as calling `Text`.
  1297.  
  1298. ### Fonts
  1299.  
  1300. Already discussed in the common parameters section. Either string or a tuple.
  1301.  
  1302. ### Color in PySimpleGUI are in one of two formats - color name or RGB value.
  1303.  
  1304. Individual colors are specified using either the color names as defined in tkinter or an RGB string of this format:
  1305.  
  1306. "#RRGGBB" or "darkblue"
  1307.  
  1308. ### `auto_size_text `
  1309. A `True` value for `auto_size_text`, when placed on Text Elements, indicates that the width of the Element should be shrunk do the width of the text. The default setting is True.
  1310.  
  1311.  
  1312. ### Chortcut functions
  1313. The shorthand functions for `Text` are `Txt` and `T`
  1314.  
  1315. ### Events `enable_events`
  1316.  
  1317. If you set the parameter `enable_events` or `click_submits` then you will get an event if the user clicks on the Text.
  1318.  
  1319.  
  1320. ### Text Methods
  1321.  
  1322. #### Update
  1323.  
  1324.  
  1325. If you want to change the text, font, or colors after the element has been created, then use the `Update` method.
  1326.  
  1327. <!-- <+Text methods+> -->
  1328.  
  1329. ```python
  1330. Update(value = None, background_color=None, text_color=None, font=None, visible=None)
  1331. ```
  1332. | name | meaning |
  1333. | - | - |
  1334. | value | new value to set text element to |
  1335. | background_color | new background color |
  1336. | text_color | text color to display |
  1337. | font | font to use to display |
  1338. | visible | visibility |
  1339. | | |
  1340.  
  1341.  
  1342.  
  1343. <!-- %!% -->
  1344. ## Multiline Element
  1345.  
  1346. layout = [[sg.Multiline('This is what a Multi-line Text Element looks like', size=(45,5))]]
  1347.  
  1348. ![multiline](https://user-images.githubusercontent.com/13696193/44959853-b139a180-aec3-11e8-972f-f52188510c88.jpg)
  1349.  
  1350. This Element doubles as both an input and output Element.
  1351.  
  1352. <!-- <+Multiline+> -->
  1353.  
  1354. <!--
  1355. ```python
  1356. Multiline(default_text='',
  1357. enter_submits=False,
  1358. disabled=False,
  1359. autoscroll=False,
  1360. size=(None, None),
  1361. auto_size_text=None,
  1362. background_color=None,
  1363. text_color=None,
  1364. change_submits=False,
  1365. enable_events=False,
  1366. do_not_clear=False,
  1367. key=None,
  1368. focus=False,
  1369. font=None,
  1370. pad=None,
  1371. tooltip=None
  1372. right_click_menu=None,
  1373. visible=True)
  1374. ```
  1375. |name|meaning|
  1376. |-|-|
  1377. | default_text | Text to display in the text box |
  1378. | change_submits | Bool. If True, pressing Enter key submits window |
  1379. | anable_events | Bool. same as change_submits|
  1380. | autoscroll | Bool. Causes "cursor" to always be at the end of the text |
  1381. | size | Element's size |
  1382. | right_click_menu | menu definition to displat if right clicked |
  1383. | auto_size_text | Bool. Change width to match size of text |
  1384. ||| -->
  1385.  
  1386. ### Multiline Methods
  1387.  
  1388.  
  1389. <!-- <+Multiline methods+> -->
  1390.  
  1391. ```python
  1392. Update(value=None,
  1393. disabled=None,
  1394. append=False,
  1395. font=None,
  1396. text_color=None,
  1397. background_color=None)
  1398.  
  1399. Update(self, value=None, disabled=None, append=False, font=None, text_color=None, background_color=None)value=None, disabled=None, append=False):
  1400. ```
  1401. |name|meaning|
  1402. |-|-|
  1403. | value | string to set the text field to|
  1404. | disabled | set to True to disable the element|
  1405. | append | rather than replacing the current text with new text, add the new text onto the end|
  1406. |||
  1407.  
  1408. <!-- %!% -->
  1409. ## Output Element
  1410. Output re-routes `Stdout` to a scrolled text box.
  1411.  
  1412. Whatever you print will show up in this window.
  1413.  
  1414. Note that you will NOT see what you print until you call either window.Read or window.Refresh. If you want to immediately see what was printed, call window.Refresh() immediately after your print statement.
  1415.  
  1416. ```python
  1417. layout = [[sg.Output(size=(80,10)]]
  1418. ```
  1419.  
  1420. ![output](https://user-images.githubusercontent.com/13696193/44959863-b72f8280-aec3-11e8-8caa-7bc743149953.jpg)
  1421.  
  1422. <!-- <+Output+> -->
  1423.  
  1424. <!--
  1425. ```python
  1426. Output(size=(None, None),
  1427. background_color=None,
  1428. text_color=None,
  1429. pad=None,
  1430. font=None,
  1431. tooltip=None,
  1432. right_click_menu=None,
  1433. key=None,
  1434. visible=True)
  1435. ```
  1436.  
  1437. size - Size of Output Element (width, height) in characters
  1438. You should be quite familiar with these parameters by now. If not, read able another element or read about common parameters.
  1439. -->
  1440.  
  1441.  
  1442. ## Input Elements
  1443. These make up the majority of the window definition. Optional variables at the Element level override the window level values (e.g. `size` is specified in the Element). All input Elements create an entry in the list of return values. A Text Input Element creates a string in the list of items returned.
  1444.  
  1445. ## Text Input Element Shortcuts (Input, In)
  1446.  
  1447. ```python
  1448. layout = [[sg.InputText('Default text')]]
  1449. ```
  1450.  
  1451. ![inputtext 2](https://user-images.githubusercontent.com/13696193/44959861-b5fe5580-aec3-11e8-8040-53ec241b5079.jpg)
  1452.  
  1453. <!-- <+InputText+> -->
  1454.  
  1455. <!--
  1456. ```python
  1457. def InputText(default_text ='',
  1458. size=(None, None),
  1459. disabled=False,
  1460. auto_size_text=None,
  1461. password_char='',
  1462. justification=None,
  1463. background_color=None,
  1464. text_color=None,
  1465. font=None,
  1466. tooltip=None,
  1467. change_submits=False
  1468. do_not_clear=False,
  1469. key=None,
  1470. focus=False,
  1471. right_click_menu=None,
  1472. pad=None,
  1473. vitible=True):
  1474. ```
  1475.  
  1476. .
  1477. |name|meaning|
  1478. |-|-|
  1479. | default_text | str. Text initially shown in the input box |
  1480. | size | (width, height) of element in characters |
  1481. | auto_size_text | Bool. True is element should be sized to fit text |
  1482. | disabled | Bool. If True the input is disabled |
  1483. | password_char | Character that will be used to replace each entered character. Setting to a value indicates this field is a password entry field |
  1484. | background_color | color to use for the input field background |
  1485. | text_color | color to use for the typed text |
  1486. | font | font used for the element|
  1487. | tooltip | what is shown when hovered over element (doesn't appear to work)|
  1488. | change_submits | if True, will cause a Window.Read to return if a button fills in the value|
  1489. | do_not_clear | Bool. Normally windows clear when read, turn off clearing with this flag. |
  1490. | key | Dictionary key to use for return values |
  1491. | focus | Bool. True if this field should capture the focus (moves cursor to this field) |
  1492. | pad | amount of room in pixels to leave around the element|
  1493. |||
  1494. -->
  1495.  
  1496.  
  1497. There are two methods that can be called:
  1498.  
  1499. ```
  1500. Input.Update(new_Value) - sets the input to new_value
  1501. Input.Get() - returns the current value of the field.
  1502. ```
  1503.  
  1504. Shorthand functions that are equivalent to `InputText` are `Input` and `In`
  1505.  
  1506. #### do_not_clear Parameter
  1507.  
  1508. **Important** - This trips a lot of people up. If you do not set the `do_not_clear` parameter then the input field will clear when an event takes place. The behavior is a "forms" style window development. The assumption is that you want the field to clear. If you are writing a chat program then you're thankful. The rest of you, I'm sorry.
  1509.  
  1510. ### TextInput Methods
  1511. ```python
  1512. Update(value=None, disabled=None):
  1513. Get()
  1514. ```
  1515. |name|meaning|
  1516. |-|-|
  1517. | Update | Change the Element |
  1518. | value | new value to display in field |
  1519. | disabled | if True will disable the element |
  1520. | Get | Returns the current value for the element (you can get also from a call to Read) |
  1521. |||
  1522.  
  1523. <!-- %!% -->
  1524. ## Combo Element
  1525. Also known as a drop-down list. Only required parameter is the list of choices. The return value is a string matching what's visible on the GUI.
  1526.  
  1527. ```python
  1528. layout = [[sg.InputCombo(['choice 1', 'choice 2'])]]
  1529. ```
  1530.  
  1531. ![combobox](https://user-images.githubusercontent.com/13696193/44959860-b565bf00-aec3-11e8-82fe-dbe41252458b.jpg)
  1532.  
  1533.  
  1534. <!-- <+Combo+> -->
  1535.  
  1536. <!--
  1537. ```
  1538. InputCombo(values,
  1539. default_value=None
  1540. size=(None, None)
  1541. auto_size_text=None
  1542. background_color=None
  1543. text_color=None
  1544. change_submits=False
  1545. enable_events=False
  1546. readonly=True
  1547. disabled=False
  1548. key=None
  1549. pad=None
  1550. tooltip=None
  1551. visible=True)
  1552. ```
  1553.  
  1554. |name|meaning|
  1555. |-|-|
  1556. | values | Choices to be displayed. List of strings |
  1557. | default_value | which value should be initially chosen |
  1558. | size | (width, height) of element in characters |
  1559. | auto_size_text | Bool. True if size should fit the text length |
  1560. | background_color | color to use for the input field background |
  1561. | text_color | color to use for the typed text |
  1562. | change_submits | Bool. If set causes Read to immediately return if the selected value changes |
  1563. | disabled | Bool. If set will disable changes |
  1564. | readonly | Bool. If set user cannot change the values to choose from |
  1565. | key | Dictionary key to use for return values |
  1566. | pad | (x,y) Amount of padding to put around element in pixels |
  1567. | tooltip | Text string. If set, hovering over field will popup the text |
  1568. -->
  1569.  
  1570. Shortcut functions - Combo, DropDown, Drop
  1571.  
  1572. ### Combo Methods
  1573. ```python
  1574. Update(value=None, values=None, set_to_index=None, disabled=None, readonly=None)
  1575. ```
  1576. value - change which value is current selected
  1577. values - change list of choices
  1578. set_to_index - change selection to a particular choice
  1579. disable - if True will disable element
  1580. readonly - if True will make element readonly
  1581.  
  1582. <!-- %!% -->
  1583. ## Listbox Element
  1584. The standard listbox like you'll find in most GUIs. Note that the return values from this element will be a ***list of results, not a single result***. This is because the user can select more than 1 item from the list (if you set the right mode).
  1585.  
  1586. ```python
  1587. layout = [[sg.Listbox(values=['Listbox 1', 'Listbox 2', 'Listbox 3'], size=(30, 6))]]
  1588. ```
  1589.  
  1590. ![listbox 2](https://user-images.githubusercontent.com/13696193/44959859-b4cd2880-aec3-11e8-881c-1e369d5c6337.jpg)
  1591.  
  1592.  
  1593. <!-- <+Listbox+> -->
  1594.  
  1595. <!--
  1596. ```
  1597. Listbox(values
  1598. default_values=None
  1599. select_mode=None
  1600. change_submits=False
  1601. bind_return_key=False
  1602. size=(None, None)
  1603. disabled = False,
  1604. auto_size_text=None
  1605. font=None
  1606. background_color=None
  1607. text_color=None
  1608. key=None
  1609. pad=None
  1610. right_click_menu=None
  1611. tooltip=None,
  1612. visible=True):
  1613. ```
  1614.  
  1615.  
  1616. - values - Choices to be displayed. List of strings
  1617. - select_mode - Defines how to list is to operate.
  1618. - Choices include constants or strings:
  1619. - Constants version:
  1620. - LISTBOX_SELECT_MODE_BROWSE
  1621. - LISTBOX_SELECT_MODE_EXTENDED
  1622. - LISTBOX_SELECT_MODE_MULTIPLE
  1623. - LISTBOX_SELECT_MODE_SINGLE - the default
  1624. - Strings version:
  1625. - 'browse'
  1626. - 'extended'
  1627. - 'multiple'
  1628. - 'single'
  1629. - change_submits - if True, the window read will return with a button value of ''
  1630. - bind_return_key - if the focus is on the listbox and the user presses return key, or if the user double clicks an item, then the read will return
  1631. - size - (width, height) of element in characters
  1632. - disapled - Bool. If True element is disabled
  1633. - auto_size_text - Bool. True if size should fit the text length
  1634. - background_color - color to use for the input field background
  1635. - font - font to use for items in list
  1636. - text_color - color to use for the typed text
  1637. - key - Dictionary key to use for return values and to find element
  1638. - pad - amount of padding to use when packing
  1639. - tooltip - tooltip text -->
  1640.  
  1641.  
  1642. The `select_mode` option can be a string or a constant value defined as a variable. Generally speaking strings are used for these kinds of options.
  1643.  
  1644. ListBoxes can cause a window to return from a Read call. If the flag change_submits is set, then when a user makes a selection, the Read immediately returns.
  1645. Another way ListBoxes can cause Reads to return is if the flag bind_return_key is set. If True, then if the user presses the return key while an entry is selected, then the Read returns. Also, if this flag is set, if the user double-clicks an entry it will return from the Read.
  1646.  
  1647. ### Listbox Methods
  1648. ```python
  1649. Update(values=None, disabled=None)
  1650. SetValue(values)
  1651. GetListValues()
  1652. ```
  1653.  
  1654. |name|meaning|
  1655. |-|-|
  1656. | Update | Change element |
  1657. | values | new list of choices |
  1658. | disabled | if True disables the element |
  1659. | SetValue | Sets selection to one or more values |
  1660. | GetListValues | Return the list of values to choose from |
  1661. |||
  1662.  
  1663. <!-- %!% -->
  1664. ## Slider Element
  1665.  
  1666. Sliders have a couple of slider-specific settings as well as appearance settings. Examples include the `orientation` and `range` settings.
  1667.  
  1668. layout = [[sg.Slider(range=(1,500), default_value=222, size=(20,15), orientation='horizontal', font=('Helvetica', 12))]]
  1669.  
  1670. ![slider](https://user-images.githubusercontent.com/13696193/44959858-b4349200-aec3-11e8-9e25-c0fcf025d19e.jpg)
  1671.  
  1672.  
  1673. <!-- <+Slider+> -->
  1674.  
  1675. <!--
  1676. Slider(range=(None,None),
  1677. default_value=None,
  1678. resolution=None,
  1679. orientation=None,
  1680. border_width=None,
  1681. relief=None,
  1682. change_submits=False,
  1683. disabled=False,
  1684. size=(None, None),
  1685. font=None,
  1686. background_color=None,
  1687. text_color=None,
  1688. key=None,
  1689. pad=None,
  1690. tooltip=None,
  1691. visible=True)
  1692.  
  1693. range - (min, max) slider's range
  1694. default_value - default setting (within range)
  1695. resolution - how much each 'tick' should represent. Default = 1
  1696. orientation - 'horizontal' or 'vertical' ('h' or 'v' work)
  1697. border_width - how deep the widget looks
  1698. relief - relief style. Values are same as progress meter relief values. Can be a constant or a string:
  1699.  
  1700. - RELIEF_RAISED= 'raised'
  1701. - RELIEF_SUNKEN= 'sunken'
  1702. - RELIEF_FLAT= 'flat'
  1703. - RELIEF_RIDGE= 'ridge'
  1704. - RELIEF_GROOVE= 'groove'
  1705. - RELIEF_SOLID = 'solid'
  1706.  
  1707. size - (width, height) of element in characters
  1708. disabled - Bool If True slider is disabled
  1709. auto_size_text - Bool. True if size should fit the text
  1710. background_color - color to use for the input field background
  1711. text_color - color to use for the typed text
  1712. change_submits - causes window read to immediately return if the checkbox value changes
  1713. key- Dictionary key to use for return values
  1714. tooltip - Tooltip to display when hovered over wlement
  1715. -->
  1716.  
  1717. ### Qt Sliders
  1718.  
  1719. There is an important difference between Qt and tkinter sliders. On Qt, the slider values must be integer, not float. If you want your slider to go from 0.1 to 1.0, then make your slider go from 1 to 10 and divide by 10. It's an easy math thing to do and not a big deal. Just deal with it.... you're writing software after all. Presumably you know how to do these things. ;-)
  1720.  
  1721.  
  1722. ### Slider Methods
  1723. ```python
  1724. Update(self, value=None, range=(None, None), disabled=None, visible=None):
  1725. ```
  1726.  
  1727. value - set current selection to value
  1728. range - change range of valid values
  1729. disabled - if True disables element
  1730.  
  1731. <!-- %!% -->
  1732. ## Radio Element
  1733.  
  1734. Creates one radio button that is assigned to a group of radio buttons. Only 1 of the buttons in the group can be selected at any one time.
  1735.  
  1736. ```python
  1737. layout = [
  1738. [sg.Radio('My first Radio!', "RADIO1", default=True),
  1739. sg.Radio('My second radio!', "RADIO1")]
  1740. ]
  1741. ```
  1742.  
  1743. ![radio](https://user-images.githubusercontent.com/13696193/44959857-b4349200-aec3-11e8-8e2d-e6a49ffbd0b6.jpg)
  1744.  
  1745. <!-- <+Radio+> -->
  1746.  
  1747. <!--
  1748. Radio(text,
  1749. group_id,
  1750. default=False,
  1751. size=(None, None),
  1752. disabled = False,
  1753. auto_size_text=None,
  1754. font=None,
  1755. background_color = None,
  1756. text_color = None,
  1757. key = None,
  1758. pad = None,
  1759. tooltip = None,
  1760. visible=True)
  1761.  
  1762. |name|meaning|
  1763. |-|-|
  1764. | text| Text to display next to button|
  1765. | group_id| Groups together multiple Radio Buttons. Can be any value|
  1766. | default| Bool. Initial state|
  1767. | size| (width, height) size of element in characters|
  1768. | auto_size_text| Bool. True if should size width to fit text|
  1769. | font| Font type and size for text display|
  1770. | background_color| color to use for the background|
  1771. | text_color| color to use for the text|
  1772. | key| Dictionary key to use for return values|
  1773. | pad| padding around element|
  1774. | tooltip| tooltip to show when mouse hovered over element|
  1775. |||
  1776. -->
  1777.  
  1778. ### Radio Button Methods
  1779. ```python
  1780. Update(value=None, disabled=None, visible=None)
  1781. ```
  1782.  
  1783. |name|meaning|
  1784. |-|-|
  1785. | value | Bool. if True change to selected |
  1786. | disabled | if True disables the element |
  1787. |||
  1788.  
  1789. <!-- %!% -->
  1790. ## Checkbox Element
  1791. Checkbox elements are like Radio Button elements. They return a bool indicating whether or not they are checked.
  1792.  
  1793. layout = [[sg.Checkbox('My first Checkbox!', default=True), sg.Checkbox('My second Checkbox!')]]
  1794.  
  1795. ![checkbox](https://user-images.githubusercontent.com/13696193/44959906-6f5d2b00-aec4-11e8-9c8a-962c787f0286.jpg)
  1796.  
  1797.  
  1798. <!-- <+Checkbox+> -->
  1799.  
  1800. <!-- Checkbox(text,
  1801. default=False,
  1802. size=(None, None),
  1803. auto_size_text=None,
  1804. font=None,
  1805. background_color = None,
  1806. text_color = None,
  1807. change_submits = False
  1808. disabled = False,
  1809. key = None,
  1810. pad = None,
  1811. tooltip = None,
  1812. visible=True):
  1813.  
  1814.  
  1815. | text | Text to display next to checkbox |
  1816. | default | Bool + None. Initial state. True = Checked, False = unchecked, None = Not available (grayed out) |
  1817. | size | (width, height) size of element in characters |
  1818. | auto_size_text | Bool. True if should size width to fit text |
  1819. | disabled | Bool. If True element is disabled |
  1820. | font | Font type and size for text display |
  1821. | background_color | color to use for the background |
  1822. | text_color | color to use for the typed text |
  1823. | change_submits | causes window read to immediately return if the checkbox value changes |
  1824. | key | Dictionary key to use for return values |
  1825. | pad | Padding around element in window |
  1826. | tooltip | text to show when mouse is hovered over element |
  1827. -->
  1828.  
  1829. Shortcut functions - CBox, CB, Check
  1830.  
  1831. ### Checkbox Methods
  1832. ```python
  1833. Update(value=None, disabled=None, visible=None)
  1834. Get()
  1835. ```
  1836.  
  1837. |name|meaning|
  1838. |-|-|
  1839. | Update| changes the element|
  1840. | value| Bool if True checks the checkbox|
  1841. | disabled| if True disables the element|
  1842. | Get| returns current state|
  1843. |||
  1844.  
  1845.  
  1846.  
  1847.  
  1848. <!-- %!% -->
  1849. ## Spin Element
  1850.  
  1851. An up/down spinner control. The valid values are passed in as a list.
  1852.  
  1853. layout = [[sg.Spin([i for i in range(1,11)], initial_value=1), sg.Text('Volume level')]]
  1854.  
  1855. ![spinner](https://user-images.githubusercontent.com/13696193/44959855-b1d23800-aec3-11e8-9f51-afb2109879da.jpg)
  1856.  
  1857. <!-- <+Spin+> -->
  1858.  
  1859. <!--
  1860. Spin(values,
  1861. intiial_value=None,
  1862. disabled = False,
  1863. size=(None, None),
  1864. change_submits = False,
  1865. auto_size_text=None,
  1866. font=None,
  1867. background_color = None,
  1868. text_color = None,
  1869. key = None.
  1870. pad = None,
  1871. tooltip = None,
  1872. visible=True):
  1873.  
  1874.  
  1875.  
  1876. Parameter definitions
  1877.  
  1878. values - List of valid values
  1879. initial_value - String with initial value
  1880. size - (width, height) size of element in characters
  1881. auto_size_text - Bool. True if should size width to fit text
  1882. font - Font type and size for text display
  1883. disabled - Bool. If True element is disabled
  1884. background_color - color to use for the background
  1885. text_color - color to use for the typed text
  1886. change_submits - causes window read to immediately return if the spinner value changes
  1887. key = Dictionary key to use for return values
  1888. pad - padding around element in the window
  1889. tooltip - text to show when mouse hovered over element -->
  1890.  
  1891.  
  1892. ### Qt Differences - `values` is a range!
  1893.  
  1894. Note that Qt does not allow arbitrary spinner values. With PySimpleGUI-tkinter you can have any values in your list. In Qt they must be integers. Yea, it kinda sucks. I'm working on it.
  1895.  
  1896. On Qt values is a tuple representing a range. On plain PySimpleGUI this value is a list of items. Make sure on the plain version you specify items as a list using [] and not a generator using ().
  1897.  
  1898.  
  1899. ### Spin Methods
  1900. ```python
  1901. Update(value=None, values=None, disabled=None, visible=None)
  1902. ```
  1903. value - set the current value
  1904. values - set available choices
  1905. disabled - if True disables the element
  1906.  
  1907. <!-- %!% -->
  1908. ## Image Element
  1909.  
  1910. Images can be placed in your window provide they are in PNG, GIF, PPM/PGM format. JPGs cannot be shown because tkinter does not naively support JPGs. You can use the Python Imaging Library (PIL) package to convert your image to PNG prior to calling PySimpleGUI if your images are in JPG format.
  1911.  
  1912.  
  1913. <!-- <+Image+> -->
  1914.  
  1915. <!--
  1916. ```python
  1917. Image(filename=None,
  1918. data=None,
  1919. data_base64=None,
  1920. background_color=None,
  1921. size=(None,None),
  1922. pad=None,
  1923. key=None,
  1924. tooltip=None,
  1925. click_submits=False,
  1926. enable_events=False,
  1927. visible=True,
  1928. right_click_menu=None,
  1929. size_px=(None,None)
  1930. visible=True)
  1931. ```
  1932. Parameter definitions
  1933.  
  1934. filename - file name if the image is in a file
  1935. data - if image is in RAM (PIL format?)
  1936. data_base64 - image in base64 format
  1937. background_color - Color of background
  1938. size - Size (Width, Height) of image in pixels
  1939. pad - Padding around Element in the window
  1940. key - Key used to find the element
  1941. tooltip - text to show when mouse if hovered over image
  1942. click_submits, enable_events - if True returns event when image is clicked
  1943. visible - if False will create image as hidden
  1944. size_px - size of image in pixels
  1945. -->
  1946.  
  1947. ### `Update` Method
  1948.  
  1949. Like other Elements, the Image Element has an `Update` method. Call Update if you want to change the image.
  1950.  
  1951. def Update(self, filename=None, data=None, visible=None):
  1952.  
  1953.  
  1954. Choose **either** a filename or in-ram data image to use to replace current image
  1955.  
  1956. ### `UpdateAnimation` Method for Animated GIFs
  1957.  
  1958. ![loading animation](https://user-images.githubusercontent.com/13696193/51280871-d2041e80-19ae-11e9-8757-802eb95352ed.gif)
  1959.  
  1960.  
  1961. Starting in version 3.23 you can specify an animated GIF as an image and can animate the GIF by calling `UpdateAnimation`. Exciting stuff!
  1962.  
  1963. ```python
  1964. UpdateAnimation(source,
  1965. time_between_frames=0)
  1966. ```
  1967. `source` can be a filename ***or*** a base64 bytes variable (unlike other calls that split out the filename parameter and base64 parameter into 2 parameters.
  1968.  
  1969. `time_between_frames` is an optional parameter. It will keep track of the amount of time between frame changes for you to give you a smooth animation. With this parameter you can call the function as often as you want and it will advance to the next frame only after the correct amount of time has lapsed.
  1970.  
  1971. You can call the method without setting the `time_between_frames` value and it will show a frame and immediately move on to the next frame. This enables you to do the inter-frame timing.
  1972.  
  1973.  
  1974.  
  1975.  
  1976. <!-- %!% -->
  1977. ## Button Element
  1978.  
  1979. **MAC USERS** - Macs suck when it comes to tkinter and button colors. It sucks so badly with colors that the `LookAndFeel` call is disabled. You cannot change button colors for Macs. You're stuck with the system default color if you are using the tkinter version of PySimpleGUI. The Qt version does not have this issue.
  1980.  
  1981. Buttons are the most important element of all! They cause the majority of the action to happen. After all, it's a button press that will get you out of a window, whether it be Submit or Cancel, one way or another a button is involved in all windows. The only exception is to this is when the user closes the window using the "X" in the upper corner which means no button was involved.
  1982.  
  1983. The Types of buttons include:
  1984. * Folder Browse
  1985. * File Browse
  1986. * Files Browse
  1987. * File SaveAs
  1988. * File Save
  1989. * Close window (normal button)
  1990. * Read window
  1991. * Realtime
  1992. * Calendar Chooser
  1993. * Color Chooser
  1994.  
  1995.  
  1996. Close window - Normal buttons like Submit, Cancel, Yes, No, do NOT close the window... they used to. Now to close a window you need to use a CloseButton / CButton.
  1997.  
  1998. Folder Browse - When clicked a folder browse dialog box is opened. The results of the Folder Browse dialog box are written into one of the input fields of the window.
  1999.  
  2000. File Browse - Same as the Folder Browse except rather than choosing a folder, a single file is chosen.
  2001.  
  2002. Calendar Chooser - Opens a graphical calendar to select a date.
  2003.  
  2004. Color Chooser - Opens a color chooser dialog
  2005.  
  2006. Read window - This is a window button that will read a snapshot of all of the input fields, but does not close the window after it's clicked.
  2007.  
  2008. Realtime - This is another async window button. Normal button clicks occur after a button's click is released. Realtime buttons report a click the entire time the button is held down.
  2009.  
  2010. Most programs will use a combination of shortcut button calls (Submit, Cancel, etc), normal Buttons which leave the windows open and CloseButtons that close the window when clicked.
  2011.  
  2012. Sometimes there are multiple names for the same function. This is simply to make the job of the programmer quicker and easier. Or they are old names that are no longer used but kept around so that existing programs don't break.
  2013.  
  2014. The 4 primary windows of PySimpleGUI buttons and their names are:
  2015.  
  2016. 1. `Button`= `ReadButton` = `RButton` = `ReadFormButton` (old style... use Button instead)
  2017. 2. `CloseButton` = `CButton`
  2018. 3. `RealtimeButton`
  2019. 4. `DummyButton`
  2020.  
  2021. You will find the long-form names in the older programs. ReadButton for example.
  2022.  
  2023. In Oct 2018, the definition of Button changed. Previously Button would CLOSE the window when clicked. It has been changed so the Button calls will leave the window open in exactly the same way as a ReadButton. They are the same calls now. To enables windows to be closed using buttons, a new button was added... `CloseButton` or `CButton`.
  2024.  
  2025. The most basic Button element call to use is `Button`
  2026.  
  2027. <!-- <+Button+> -->
  2028.  
  2029. <!-- Button(button_text=''
  2030. button_type=BUTTON_TYPE_CLOSES_WIN
  2031. target=(None, None)
  2032. tooltip=None
  2033. file_types=(("ALL Files", "*.*"),)
  2034. initial_folder=None
  2035. disabled = False
  2036. image_filename=None
  2037. image_data=None
  2038. image_size=(None, None)
  2039. image_subsample=None
  2040. border_width=None
  2041. size=(None, None)
  2042. auto_size_button=None
  2043. button_color=None
  2044. default_value = None
  2045. font=None
  2046. bind_return_key=False
  2047. focus=False
  2048. pad=None
  2049. key=None,
  2050. visible=True):
  2051.  
  2052. Parameters
  2053.  
  2054. button_text - Text to be displayed on the button
  2055. button_type - You should NOT be setting this directly
  2056. target - key or (row,col) target for the button
  2057. tooltip - tooltip text for the button
  2058. file_types - the filetypes that will be used to match files
  2059. initial_folder - starting path for folders and files
  2060. disabled = Bool If True button is disabled
  2061. image_filename - image filename if there is a button image
  2062. image_data - in-RAM image to be displayed on button
  2063. image_size - size of button image in pixels
  2064. image_subsample - amount to reduce the size of the image
  2065. border_width - width of border around button in pixels
  2066. size - size in characters
  2067. auto_size_button - True if button size is determined by button text
  2068. button_color - (text color, backound color)
  2069. default_value - initial value for buttons that hold information
  2070. font - font to use for button text
  2071. bind_return_key - If True the return key will cause this button to fire
  2072. focus - if focus should be set to this button
  2073. pad - (x,y) padding in pixels for packing the button
  2074. key - key used for finding the element
  2075. -->
  2076. ### Shortcut, Pre-defined Buttons
  2077. These Pre-made buttons are some of the most important elements of all because they are used so much. They all basically do the same thing, set the button text to match the function name and set the parameters to commonly used values. If you find yourself needing to create a custom button often because it's not on this list, please post a request on GitHub. . They include:
  2078.  
  2079. OK
  2080. Ok
  2081. Submit
  2082. Cancel
  2083. Yes
  2084. No
  2085. Exit
  2086. Quit
  2087. Help
  2088. Save
  2089. SaveAs
  2090. FileBrowse
  2091. FilesBrowse
  2092. FileSaveAs
  2093. FolderBrowse
  2094.  
  2095. **IMPORT NOTE ABOUT SHORTCUT BUTTONS**
  2096. Prior to release 3.11.0, these buttons closed the window. Starting with 3.11 they will not close the window. They act like RButtons (return the button text and do not close the window)
  2097.  
  2098. If you are having trouble with these buttons closing your window, please check your installed version of PySimpleGUI by typing `pip list` at a command prompt. Prior to 3.11 these buttons close your window.
  2099.  
  2100. Using older versions, if you want a Submit() button that does not close the window, then you would instead use RButton('Submit'). Using the new version, if you want a Submit button that closes the window like the sold Submit() call did, you would write that as `CloseButton('Submit')` or `CButton('Submit')`
  2101.  
  2102.  
  2103. layout = [[sg.OK(), sg.Cancel()]]
  2104.  
  2105. ![ok cancel 3](https://user-images.githubusercontent.com/13696193/44959927-aa5f5e80-aec4-11e8-86e1-5dc0b3a2b803.jpg)
  2106.  
  2107.  
  2108.  
  2109. ### Button targets
  2110.  
  2111. The `FileBrowse`, `FolderBrowse`, `FileSaveAs` , `FilesSaveAs`, `CalendarButton`, `ColorChooserButton` buttons all fill-in values into another element located on the window. The target can be a Text Element or an InputText Element. The location of the element is specified by the `target` variable in the function call.
  2112.  
  2113. The Target comes in two forms.
  2114. 1. Key
  2115. 2. (row, column)
  2116.  
  2117. Targets that are specified using a key will find its target element by using the target's key value. This is the "preferred" method.
  2118.  
  2119. If the Target is specified using (row, column) then it utilizes a grid system. The rows in your GUI are numbered starting with 0. The target can be specified as a hard coded grid item or it can be relative to the button.
  2120.  
  2121. The (row, col) targeting can only target elements that are in the same "container". Containers are the Window, Column and Frame Elements. A File Browse button located inside of a Column is unable to target elements outside of that Column.
  2122.  
  2123. The default value for `target` is `(ThisRow, -1)`. `ThisRow` is a special value that tells the GUI to use the same row as the button. The Y-value of -1 means the field one value to the left of the button. For a File or Folder Browse button, the field that it fills are generally to the left of the button is most cases. (ThisRow, -1) means the Element to the left of the button, on the same row.
  2124.  
  2125. If a value of `(None, None)` is chosen for the target, then the button itself will hold the information. Later the button can be queried for the value by using the button's key.
  2126.  
  2127. Let's examine this window as an example:
  2128.  
  2129.  
  2130. ![file browse](https://user-images.githubusercontent.com/13696193/44959944-d1b62b80-aec4-11e8-8a68-9d79d37b2c81.jpg)
  2131.  
  2132.  
  2133. The `InputText` element is located at (1,0)... row 1, column 0. The `Browse` button is located at position (2,0). The Target for the button could be any of these values:
  2134.  
  2135. Target = (1,0)
  2136. Target = (-1,0)
  2137.  
  2138. The code for the entire window could be:
  2139.  
  2140. layout = [[sg.T('Source Folder')],
  2141. [sg.In()],
  2142. [sg.FolderBrowse(target=(-1, 0)), sg.OK()]]
  2143.  
  2144. or if using keys, then the code would be:
  2145.  
  2146. layout = [[sg.T('Source Folder')],
  2147. [sg.In(key='input')],
  2148. [sg.FolderBrowse(target='input'), sg.OK()]]
  2149.  
  2150. See how much easier the key method is?
  2151.  
  2152. **Save & Open Buttons**
  2153.  
  2154. There are 4 different types of File/Folder open dialog box available. If you are looking for a file to open, the `FileBrowse` is what you want. If you want to save a file, `SaveAs` is the button. If you want to get a folder name, then `FolderBrowse` is the button to use. To open several files at once, use the `FilesBrowse` button. It will create a list of files that are separated by ';'
  2155.  
  2156.  
  2157. ![open](https://user-images.githubusercontent.com/13696193/45243804-2b529780-b2c3-11e8-90dc-6c9061db2a1e.jpg)
  2158.  
  2159.  
  2160. ![folder](https://user-images.githubusercontent.com/13696193/45243805-2b529780-b2c3-11e8-95ee-fec3c0b11319.jpg)
  2161.  
  2162.  
  2163. ![saveas](https://user-images.githubusercontent.com/13696193/45243807-2beb2e00-b2c3-11e8-8549-ba71cdc05951.jpg)
  2164.  
  2165.  
  2166.  
  2167. **Calendar Buttons**
  2168.  
  2169. These buttons pop up a calendar chooser window. The chosen date is returned as a string.
  2170.  
  2171. ![calendar](https://user-images.githubusercontent.com/13696193/45243374-99965a80-b2c1-11e8-8311-49777835ca40.jpg)
  2172.  
  2173. **Color Chooser Buttons**
  2174.  
  2175. These buttons pop up a standard color chooser window. The result is returned as a tuple. One of the returned values is an RGB hex representation.
  2176.  
  2177. ![color](https://user-images.githubusercontent.com/13696193/45243375-99965a80-b2c1-11e8-9779-b71bed85fab6.jpg)
  2178.  
  2179.  
  2180. **Custom Buttons**
  2181. Not all buttons are created equal. A button that closes a window is different that a button that returns from the window without closing it. If you want to define your own button, you will generally do this with the Button Element `Button`, which closes the window when clicked.
  2182.  
  2183. layout = [[sg.Button('My Button')]]
  2184.  
  2185. ![button](https://user-images.githubusercontent.com/13696193/44959862-b696ec00-aec3-11e8-9e88-4b9af0338a03.jpg)
  2186.  
  2187. All buttons can have their text changed by changing the `button_text` variable in the button call. It is this text that is returned when a window is read. This text will be what tells you which button is called so make it unique. Most of the convenience buttons (Submit, Cancel, Yes, etc) are all Buttons. Some that are not are `FileBrowse` , `FolderBrowse`, `FileSaveAs`. They clearly do not close the window. Instead they bring up a file or folder browser dialog box.
  2188.  
  2189. **Button Images**
  2190. Now this is an exciting feature not found in many simplified packages.... images on buttons! You can make a pretty spiffy user interface with the help of a few button images.
  2191.  
  2192. Your button images need to be in PNG or GIF format. When you make a button with an image, set the button background to the same color as the background. There's a button color TRANSPARENT_BUTTON that you can set your button color to in order for it to blend into the background. Note that this value is currently the same as the color as the default system background on Windows. If you want to set the button background color to the current system default, use the value COLOR_SYSTEM_DEFAULT as the background color.
  2193.  
  2194. This example comes from the `Demo Media Player.py` example program. Because it's a non-blocking button, it's defined as `RButton`. You also put images on blocking buttons by using `Button`.
  2195.  
  2196.  
  2197. sg.RButton('Restart Song', button_color=sg.TRANSPARENT_BUTTON,
  2198. image_filename=image_restart, image_size=(50, 50), image_subsample=2, border_width=0)
  2199.  
  2200. Three parameters are used for button images.
  2201.  
  2202. image_filename - Filename. Can be a relative path
  2203. image_size - Size of image file in pixels
  2204. image_subsample - Amount to divide the size by. 2 means your image will be 1/2 the size. 3 means 1/3
  2205.  
  2206. Here's an example window made with button images.
  2207.  
  2208. ![media file player](https://user-images.githubusercontent.com/13696193/43161977-9ee7cace-8f57-11e8-8ff8-3ea24b69dab9.jpg)
  2209.  
  2210. You'll find the source code in the file Demo Media Player. Here is what the button calls look like to create media player window
  2211. ```python
  2212. sg.RButton('Pause', button_color=sg.TRANSPARENT_BUTTON,
  2213. image_filename=image_pause,
  2214. image_size=(50, 50),
  2215. image_subsample=2,
  2216. border_width=0)
  2217. ```
  2218. This is one you'll have to experiment with at this point. Not up for an exhaustive explanation.
  2219.  
  2220. **Realtime Buttons**
  2221.  
  2222. Normally buttons are considered "clicked" when the mouse button is let UP after a downward click on the button. What about times when you need to read the raw up/down button values. A classic example for this is a robotic remote control. Building a remote control using a GUI is easy enough. One button for each of the directions is a start. Perhaps something like this:
  2223.  
  2224. ![robot remote](https://user-images.githubusercontent.com/13696193/44959958-ff9b7000-aec4-11e8-99ea-7450926409be.jpg)
  2225.  
  2226.  
  2227. This window has 2 button types. There's the normal "Read Button" (Quit) and 4 "Realtime Buttons".
  2228.  
  2229. Here is the code to make, show and get results from this window:
  2230.  
  2231. ```python
  2232. import PySimpleGUI as sg
  2233.  
  2234. gui_rows = [[sg.Text('Robotics Remote Control')],
  2235. [sg.T(' ' * 10), sg.RealtimeButton('Forward')],
  2236. [sg.RealtimeButton('Left'), sg.T(' ' * 15), sg.RealtimeButton('Right')],
  2237. [sg.T(' ' * 10), sg.RealtimeButton('Reverse')],
  2238. [sg.T('')],
  2239. [sg.Quit(button_color=('black', 'orange'))]
  2240. ]
  2241.  
  2242. window = sg.Window('Robotics Remote Control', auto_size_text=True).Layout(gui_rows)
  2243.  
  2244. #
  2245. # Some place later in your code...
  2246. # You need to perform a Read or Refresh call on your window every now and then or
  2247. # else it will apprear as if the program has locked up.
  2248. #
  2249. # your program's main loop
  2250. while (True):
  2251. # This is the code that reads and updates your window
  2252. event, values = window.Read(timeout=0)
  2253. if event is not None:
  2254. print(event)
  2255. if event == 'Quit' or values is None:
  2256. break
  2257.  
  2258. window.Close() # Don't forget to close your window!
  2259. ```
  2260.  
  2261. This loop will read button values and print them. When one of the Realtime buttons is clicked, the call to `window.Read` will return a button name matching the name on the button that was depressed or the key if there was a key assigned to the button. It will continue to return values as long as the button remains depressed. Once released, the Read will return timeout events until a button is again clicked.
  2262.  
  2263. **File Types**
  2264. The `FileBrowse` & `SaveAs` buttons have an additional setting named `file_types`. This variable is used to filter the files shown in the file dialog box. The default value for this setting is
  2265.  
  2266. FileTypes=(("ALL Files", "*.*"),)
  2267.  
  2268. This code produces a window where the Browse button only shows files of type .TXT
  2269.  
  2270. layout = [[sg.In() ,sg.FileBrowse(file_types=(("Text Files", "*.txt"),))]]
  2271.  
  2272. NOTE - Mac users will not be able to use the file_types parameter. tkinter has a bug on Macs that will crash the program is a file_type is attempted so that feature had to be removed. Sorry about that!
  2273.  
  2274. ***The ENTER key***
  2275. The ENTER key is an important part of data entry for windows. There's a long tradition of the enter key being used to quickly submit windows. PySimpleGUI implements this by tying the ENTER key to the first button that closes or reads a window.
  2276.  
  2277. The Enter Key can be "bound" to a particular button so that when the key is pressed, it causes the window to return as if the button was clicked. This is done using the `bind_return_key` parameter in the button calls.
  2278. If there are more than 1 button on a window, the FIRST button that is of type Close window or Read window is used. First is determined by scanning the window, top to bottom and left to right.
  2279.  
  2280.  
  2281. ### Button Methods
  2282. ```python
  2283. Update(text=None, button_color=(None, None), disabled=None, image_data=None, image_filename=None, visible=None)
  2284.  
  2285. GetText()
  2286. ```
  2287. Update - Change the button element
  2288.  
  2289. text - sets button text
  2290. button color - (text, background)
  2291. disabled - if True disables the button
  2292. image_data - sets button image to in-ram image
  2293. image_filename - sets button image using a file
  2294.  
  2295. GetText - Returns the current text shown on a button
  2296.  
  2297.  
  2298. <!-- %!% -->
  2299. ## ButtonMenu Element
  2300.  
  2301. The ButtonMenu element produces a unique kind of effect. It's a button, that when clicked, shows you a menu. It's like clicking one of the top-level menu items on a MenuBar. As a result, the menu definition take the format of a single menu entry from a normal menu definition. A normal menu definition is a list of lists. This definition is one of those lists.
  2302.  
  2303. Here is a sample definition:
  2304. ```python
  2305. ['Menu', ['&Pause Graph', 'Menu item::optional_key']]
  2306. ```
  2307. The very first string normally specifies what is shown on the menu bar. In this case, the value is **not used**. You set the text for the button using a different parameter, the `button_text` parm.
  2308.  
  2309.  
  2310. <!-- <+ButtonMenu+> -->
  2311.  
  2312. <!--
  2313. ```python
  2314. ButtonMenu( button_text,
  2315. menu_def,
  2316. tooltip=None,
  2317. disabled=False,
  2318. image_filename=None,
  2319. image_data=None,
  2320. image_size=(None, None),
  2321. image_subsample=None,
  2322. border_width=None,
  2323. size=(None, None),
  2324. auto_size_button=None,
  2325. button_color=None,
  2326. font=None,
  2327. pad=None,
  2328. key=None,
  2329. visible=True,
  2330. size_px=(None,None)):
  2331. ```
  2332. -->
  2333.  
  2334. One use of this element is to make a "fake menu bar" that has a colored background. Normal menu bars cannot have their background color changed. Not so with ButtonMenus.
  2335.  
  2336. This is the effect:
  2337.  
  2338. ![buttonmenu](https://user-images.githubusercontent.com/13696193/50387000-bc0d8180-06c0-11e9-8d17-3b22ed665e78.gif)
  2339.  
  2340. Return values for ButtonMenus are sent via the return values dictionary. If a selection is made, then an event is generated that will equal the ButtonMenu's key value. Use that key value to look up the value selected by the user. This is the same mechanism as the Menu Bar Element, but differs from the pop-up (right click) menu.
  2341.  
  2342.  
  2343.  
  2344.  
  2345.  
  2346. <!-- %!% -->
  2347. ## VerticalSeparator Element
  2348. This element has limited usefulness and is being included more for completeness than anything else. It will draw a line between elements.
  2349.  
  2350. ```python
  2351. VerticalSeparator(pad=None)
  2352. ```
  2353.  
  2354. ![snag-0129](https://user-images.githubusercontent.com/13696193/47376041-a92a0100-d6bf-11e8-8f5b-0c0df56cf0f3.jpg)
  2355.  
  2356. It works best when placed between columns or elements that span multiple rows. If on a "normal" row with elements that are only 1 row high, then it will only span that one row.
  2357.  
  2358.  
  2359.  
  2360.  
  2361. <!-- %!% -->
  2362. ## ProgressBar Element
  2363. The `ProgressBar` element is used to build custom Progress Bar windows. It is HIGHLY recommended that you use OneLineProgressMeter that provides a complete progress meter solution for you. Progress Meters are not easy to work with because the windows have to be non-blocking and they are tricky to debug.
  2364.  
  2365. The **easiest** way to get progress meters into your code is to use the `OneLineProgressMeter` API. This consists of a pair of functions, `OneLineProgressMeter` and `OneLineProgressMeterCancel`. You can easily cancel any progress meter by calling it with the current value = max value. This will mark the meter as expired and close the window.
  2366. You've already seen OneLineProgressMeter calls presented earlier in this readme.
  2367.  
  2368. sg.OneLineProgressMeter('My Meter', i+1, 1000, 'key', 'Optional message')
  2369.  
  2370. The return value for `OneLineProgressMeter` is:
  2371. `True` if meter updated correctly
  2372. `False` if user clicked the Cancel button, closed the window, or vale reached the max value.
  2373.  
  2374. #### Progress Mater in Your window
  2375. Another way of using a Progress Meter with PySimpleGUI is to build a custom window with a `ProgressBar` Element in the window. You will need to run your window as a non-blocking window. When you are ready to update your progress bar, you call the `UpdateBar` method for the `ProgressBar` element itself.
  2376.  
  2377. ![progress custom](https://user-images.githubusercontent.com/13696193/45243969-c3508100-b2c3-11e8-82bc-927d0307e093.jpg)
  2378.  
  2379. import PySimpleGUI as sg
  2380.  
  2381. # layout the window
  2382. layout = [[sg.Text('A custom progress meter')],
  2383. [sg.ProgressBar(10000, orientation='h', size=(20, 20), key='progressbar')],
  2384. [sg.Cancel()]]
  2385.  
  2386. # create the window`
  2387. window = sg.Window('Custom Progress Meter').Layout(layout)
  2388. progress_bar = window.FindElement('progressbar')
  2389. # loop that would normally do something useful
  2390. for i in range(10000):
  2391. # check to see if the cancel button was clicked and exit loop if clicked
  2392. event, values = window.Read(timeout=0)
  2393. if event == 'Cancel' or event is None:
  2394. break
  2395. # update bar with loop value +1 so that bar eventually reaches the maximum
  2396. progress_bar.UpdateBar(i + 1)
  2397. # done with loop... need to destroy the window as it's still open
  2398. window.Close())
  2399.  
  2400.  
  2401. #### Output
  2402. The Output Element is a re-direction of Stdout. Anything "printed" will be displayed in this element.
  2403.  
  2404. Output(size=(None, None))
  2405.  
  2406. Here's a complete solution for a chat-window using an Async window with an Output Element
  2407.  
  2408. import PySimpleGUI as sg
  2409.  
  2410. # Blocking window that doesn't close
  2411. def ChatBot():
  2412. layout = [[(sg.Text('This is where standard out is being routed', size=[40, 1]))],
  2413. [sg.Output(size=(80, 20))],
  2414. [sg.Multiline(size=(70, 5), enter_submits=True),
  2415. sg.RButton('SEND', button_color=(sg.YELLOWS[0], sg.BLUES[0])),
  2416. sg.Button('EXIT', button_color=(sg.YELLOWS[0], sg.GREENS[0]))]]
  2417.  
  2418. window = sg.Window('Chat Window', default_element_size=(30, 2)).Layout(layout)
  2419.  
  2420. # ---===--- Loop taking in user input and using it to query HowDoI web oracle --- #
  2421. while True:
  2422. event, value = window.Read()
  2423. if event == 'SEND':
  2424. print(value)
  2425. else:
  2426. break
  2427.  
  2428. ChatBot()
  2429.  
  2430. ### ProgressBar Methods
  2431. ```python
  2432. UpdateBar(current_count, max=None)
  2433. ```
  2434. current_count - sets the current value
  2435. max - changes the max value
  2436.  
  2437.  
  2438. <!-- %!% -->
  2439. ## Column Element
  2440. Starting in version 2.9 you'll be able to do more complex layouts by using the Column Element. Think of a Column as a window within a window. And, yes, you can have a Column within a Column if you want.
  2441.  
  2442. Columns are specified in exactly the same way as a window is, as a list of lists.
  2443.  
  2444. <!-- <+Column+> -->
  2445.  
  2446.  
  2447. <!-- ```python
  2448. Column( layout,
  2449. background_color=None,
  2450. size=(None, None),
  2451. pad=None,
  2452. scrollable=False,
  2453. vertical_scroll_only=False,
  2454. right_click_menu=None,
  2455. key=None,
  2456. visible=True)
  2457. ```
  2458. -->
  2459.  
  2460.  
  2461. Columns are needed when you have an element that has a height > 1 line on the left, with single-line elements on the right. Here's an example of this kind of layout:
  2462.  
  2463.  
  2464. ![column](https://user-images.githubusercontent.com/13696193/44959988-66b92480-aec5-11e8-9c26-316ed24a68c0.jpg)
  2465.  
  2466.  
  2467. This code produced the above window.
  2468.  
  2469.  
  2470. import PySimpleGUI as sg
  2471.  
  2472. # Demo of how columns work
  2473. # window has on row 1 a vertical slider followed by a COLUMN with 7 rows
  2474. # Prior to the Column element, this layout was not possible
  2475. # Columns layouts look identical to window layouts, they are a list of lists of elements.
  2476.  
  2477. window = sg.Window('Columns') # blank window
  2478.  
  2479. # Column layout
  2480. col = [[sg.Text('col Row 1')],
  2481. [sg.Text('col Row 2'), sg.Input('col input 1')],
  2482. [sg.Text('col Row 3'), sg.Input('col input 2')],
  2483. [sg.Text('col Row 4'), sg.Input('col input 3')],
  2484. [sg.Text('col Row 5'), sg.Input('col input 4')],
  2485. [sg.Text('col Row 6'), sg.Input('col input 5')],
  2486. [sg.Text('col Row 7'), sg.Input('col input 6')]]
  2487.  
  2488. layout = [[sg.Slider(range=(1,100), default_value=10, orientation='v', size=(8,20)), sg.Column(col)],
  2489. [sg.In('Last input')],
  2490. [sg.OK()]]
  2491.  
  2492. # Display the window and get values
  2493. # If you're willing to not use the "context manager" design pattern, then it's possible
  2494. # to collapse the window display and read down to a single line of code.
  2495. event, values = sg.Window('Compact 1-line window with column').Layout(layout).Read()
  2496.  
  2497. sg.Popup(event, values, line_width=200)
  2498.  
  2499. The Column Element has 1 required parameter and 1 optional (the layout and the background color). Setting the background color has the same effect as setting the window's background color, except it only affects the column rectangle.
  2500.  
  2501. Column(layout, background_color=None)
  2502.  
  2503. The default background color for Columns is the same as the default window background color. If you change the look and feel of the window, the column background will match the window background automatically.
  2504.  
  2505.  
  2506.  
  2507. ----
  2508. ## Frame Element (Labelled Frames, Frames with a title)
  2509.  
  2510. Frames work exactly the same way as Columns. You create layout that is then used to initialize the Frame.
  2511.  
  2512. ```python
  2513. Frame( title,
  2514. layout,
  2515. title_color=None,
  2516. background_color=None,
  2517. title_location=None,
  2518. relief=DEFAULT_FRAME_RELIEF,
  2519. size=(None, None),
  2520. font=None,
  2521. pad=None,
  2522. border_width=None,
  2523. key=None,
  2524. tooltip=None,
  2525. right_click_menu=None,
  2526. visible=True)
  2527. ```
  2528. def Frame(title - the label / title to put on frame
  2529. layout - list of rows of elements the frame contains
  2530. title_color - color of the title text
  2531. background_color - color of background
  2532. title_location - locations to put the title
  2533. relief - type of relief to use
  2534. size - size of Frame in characters. Do not use if you want frame to autosize
  2535. font - font to use for title
  2536. pad - element padding to use when packing
  2537. border_width - how thick the line going around frame should be
  2538. key - key used to location the element
  2539. tooltip - tooltip text
  2540.  
  2541.  
  2542.  
  2543. This code creates a window with a Frame and 2 buttons.
  2544.  
  2545. frame_layout = [
  2546. [sg.T('Text inside of a frame')],
  2547. [sg.CB('Check 1'), sg.CB('Check 2')],
  2548. ]
  2549. layout = [
  2550. [sg.Frame('My Frame Title', frame_layout, font='Any 12', title_color='blue')],
  2551. [sg.Submit(), sg.Cancel()]
  2552. ]
  2553.  
  2554. window = sg.Window('Frame with buttons', font=("Helvetica", 12)).Layout(layout)
  2555.  
  2556.  
  2557. ![frame element](https://user-images.githubusercontent.com/13696193/45889173-c2245700-bd8d-11e8-8f73-1e5f1be3ddb1.jpg)
  2558.  
  2559.  
  2560.  
  2561. Notice how the Frame layout looks identical to a window layout. A window works exactly the same way as a Column and a Frame. They all are "container elements". Elements that contain other elements.
  2562.  
  2563. *These container Elements can be nested as deep as you want.* That's a pretty spiffy feature, right? Took a lot of work so be appreciative. Recursive code isn't trivial.
  2564.  
  2565. <!-- %!% -->
  2566. ## Canvas Element
  2567.  
  2568.  
  2569. <!-- <+Canvas+> -->
  2570.  
  2571. <!--
  2572. ```python
  2573. Canvas(canvas=None,
  2574. background_color=None,
  2575. size=(None, None),
  2576. pad=None,
  2577. key=None,
  2578. tooltip=None,
  2579. right_click_menu=None,
  2580. visible=True)
  2581. ```
  2582. -->
  2583.  
  2584. In my opinion, the tkinter Canvas Widget is the most powerful of the tkinter widget. While I try my best to completely isolate the user from anything that is tkinter related, the Canvas Element is the one exception. It enables integration with a number of other packages, often with spectacular results.
  2585.  
  2586. ### Matplotlib, Pyplot Integration
  2587.  
  2588. One such integration is with Matploplib and Pyplot. There is a Demo program written that you can use as a design pattern to get an understanding of how to use the Canvas Widget once you get it.
  2589.  
  2590. def Canvas(canvas - a tkinter canvasf if you created one. Normally not set
  2591. background_color - canvas color
  2592. size - size in pixels
  2593. pad - element padding for packing
  2594. key - key used to lookup element
  2595. tooltip - tooltip text
  2596.  
  2597. The order of operations to obtain a tkinter Canvas Widget is:
  2598.  
  2599. figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds
  2600. # define the window layout
  2601. layout = [[sg.Text('Plot test')],
  2602. [sg.Canvas(size=(figure_w, figure_h), key='canvas')],
  2603. [sg.OK(pad=((figure_w / 2, 0), 3), size=(4, 2))]]
  2604.  
  2605. # create the window and show it without the plot
  2606. window = sg.Window('Demo Application - Embedding Matplotlib In PySimpleGUI').Layout(layout).Finalize()
  2607.  
  2608.  
  2609. # add the plot to the window
  2610. fig_photo = draw_figure(window.FindElement('canvas').TKCanvas, fig)
  2611.  
  2612. # show it all again and get buttons
  2613. event, values = window.Read()
  2614.  
  2615. To get a tkinter Canvas Widget from PySimpleGUI, follow these steps:
  2616. * Add Canvas Element to your window
  2617. * Layout your window
  2618. * Call `window.Finalize()` - this is a critical step you must not forget
  2619. * Find the Canvas Element by looking up using key
  2620. * Your Canvas Widget Object will be the found_element.TKCanvas
  2621. * Draw on your canvas to your heart's content
  2622. * Call `window.Read()` - Nothing will appear on your canvas until you call Read
  2623.  
  2624. See `Demo_Matplotlib.py` for a Recipe you can copy.
  2625.  
  2626.  
  2627. ### Canvas Methods
  2628.  
  2629. TKCanvas - not a method but a property. Returns the tkinter Canvas Widget
  2630.  
  2631.  
  2632.  
  2633. <!-- %!% -->
  2634. ## Graph Element
  2635.  
  2636. All you math fans will enjoy this Element... and all you non-math fans will enjoy it too.
  2637.  
  2638. I've found nothing to be less fun than dealing with a graphic's coordinate system from a GUI Framework. It's always upside down from what I want. (0,0) is in the upper left hand corner. In short, it's a **pain in the ass**.
  2639.  
  2640. Graph Element to the rescue. A Graph Element creates a pixel addressable canvas using YOUR coordinate system. *You* get to define the units on the X and Y axis.
  2641.  
  2642. There are 3 values you'll need to supply the Graph Element. They are:
  2643. * Size of the canvas in pixels
  2644. * The lower left (x,y) coordinate of your coordinate system
  2645. * The upper right (x,y) coordinate of your coordinate system
  2646.  
  2647. After you supply those values you can scribble all of over your graph by creating Graph Figures. Graph Figures are created, and a Figure ID is obtained by calling:
  2648. * DrawCircle
  2649. * DrawLine
  2650. * DrawPoint
  2651. * DrawRectangle
  2652. * DrawOval
  2653. * DrawImage
  2654.  
  2655. You can move your figures around on the canvas by supplying the Figure ID the x,y amount to move.
  2656.  
  2657. graph.MoveFigure(my_circle, 10, 10)
  2658.  
  2659. This Element is relatively new and may have some parameter additions or deletions. It shouldn't break your code however.
  2660.  
  2661.  
  2662. <!-- <+Graph+> -->
  2663.  
  2664.  
  2665. <!--
  2666. ```python
  2667. Graph(canvas_size,
  2668. graph_bottom_left,
  2669. graph_top_right,
  2670. background_color=None,
  2671. pad=None,
  2672. change_submits=False,
  2673. drag_submits=False
  2674. enable_events=False,
  2675. key=None,
  2676. tooltip=None,
  2677. right_click_menu=None,
  2678. visible=True)
  2679. ``` -->
  2680.  
  2681. ### Graph Methods
  2682. ```python
  2683. DrawLine(self, point_from, point_to, color='black', width=1)
  2684. DrawPoint(self, point, size=2, color='black')
  2685. DrawCircle(self, center_location, radius, fill_color=None, line_color='black')
  2686. DrawOval(self, top_left, bottom_right, fill_color=None, line_color=None)
  2687. DrawArc(self, top_left, bottom_right, extent, start_angle, style=None, arc_color='black')
  2688. DrawRectangle(self, top_left, bottom_right, fill_color=None, line_color=None)
  2689. DrawText(self, text, location, color='black', font=None, angle=0)
  2690. Erase(background_color)
  2691. DeleteFigure(figure_id)
  2692. Update()
  2693. Move(self, x_direction, y_direction)
  2694. MoveFigure(self, figure, x_direction, y_direction)
  2695. RelocateFigure(self, figure, x, y)
  2696. TKCanvas
  2697. ```
  2698. All of the Drawing methods return a "***figure***" that can be used move and delete the figure
  2699.  
  2700. DrawLine - draws a line
  2701. DrawPoint - draws a single point
  2702. DrawCircle - draws a circle
  2703. DrawOval - draws an oval
  2704. DrawArc - draws an arc
  2705. DrawRectangle - draws a rectangle
  2706. DrawText - draws text
  2707. DrawImage - places an image onto the graph
  2708. Erase - erases entire graph
  2709. Update - changes background color
  2710. Move - moves everything an x,y direction
  2711. MoveFigure - moves an individual figure by some delta
  2712. RelocateFigure - moves figure to an absolute location
  2713. DeleteFigure - delete an individual figure
  2714.  
  2715.  
  2716. <!-- %!% -->
  2717. ## Table Element
  2718.  
  2719. Out of all of the Elements, it's the Table and the Tree that are the most "problematic" in the tkinter inter and Qt implementations. They're hard is my only defense.
  2720.  
  2721. ### Known visualization problem....
  2722.  
  2723. If you click on the header, it can go into spasms for some tables. I don't understand what's causing it and it's been there evidently since the first release of Tables.
  2724.  
  2725.  
  2726. <!-- <+Table+> -->
  2727.  
  2728.  
  2729. <!-- ```python
  2730. Table( values,
  2731. headings=None,
  2732. visible_column_map=None,
  2733. col_widths=None,
  2734. def_col_width=10,
  2735. auto_size_columns=True,
  2736. max_col_width=20,
  2737. select_mode=None,
  2738. display_row_numbers=False,
  2739. num_rows=None,
  2740. row_height=None,
  2741. font=None,
  2742. justification='right',
  2743. text_color=None,
  2744. background_color=None,
  2745. alternating_row_color=None,
  2746. row_colors=None,
  2747. vertical_scroll_only=True,
  2748. size=(None,None),
  2749. change_submits=False,
  2750. enable_events=False,
  2751. bind_return_key=False,
  2752. pad=None,
  2753. key=None,
  2754. tooltip=None,
  2755. right_click_menu=None,
  2756. visible=True):
  2757.  
  2758. ```
  2759.  
  2760. values - Your table's array
  2761. headings - list of strings representing your headings, if you have any
  2762. visible_column_map - list of bools. If True, column in that position is shown. Defaults to all columns
  2763. col_widths - list of column widths
  2764. def_col_width - default column width. defaults to 10
  2765. auto_size_columns - bool. If True column widths are determined by table contents
  2766. max_col_width - maximum width of a column. defaults to 25
  2767. select_mode - table rows can be selected, but doesn't currently do anything
  2768. display_row_numbers - bool. If True shows numbers next to rows
  2769. num_rows = the number of rows to display at a time (same as size[0])
  2770. row_height = number of pixels high a row should be. Normally left as default value
  2771. font - font for table entries
  2772. justification - left, right, center
  2773. text_color - color of text
  2774. alternating row color - if set will change background color for alternating rows
  2775. row_colors - list of tuples representing (row_number, color) e.g. row_colors = ((5, 'white', 'blue'), (0,'red'), (15,'yellow'))
  2776. vertical_scroll_only - if True will not show a horizontal scrollbar. NOTE - will have to disable to get horizontal scrollbars
  2777. background_color - cell background color
  2778. size - (None, number of rows) - don't use, use num_rows instead
  2779. enable_events - will return a 'row selected' event when row is selected
  2780. change_submits - the old way of indicating enable_events
  2781. bind_return_key - returns event if a double click or a return key is pressed while row is highlighted
  2782. pad - element padding for packing
  2783. key - key used to lookup element
  2784. tooltip - tooltip text -->
  2785.  
  2786.  
  2787. ### Read return values from Table Element
  2788.  
  2789. The values returned from a `Window.Read` call for the Tree Element are a list of row numbers that are currently highlighted.
  2790.  
  2791. ### Update Call
  2792.  
  2793. The Update method can be used to make changes to a table that's already been displayed. The call takes a single parameter, values, which is the new table to display. The entire table is replaced.
  2794.  
  2795. ```python
  2796. def Update(self, values=None):
  2797. ```
  2798. `values` is a table containing your rows just like you passed in when creating the Table Element.
  2799.  
  2800. <!-- %!% -->
  2801. ## Tree Element
  2802.  
  2803. The Tree Element and Table Element are close cousins. Many of the parameters found in the Table Element apply to Tree Elements. In particular the heading information, column widths, etc.
  2804.  
  2805. <!-- <+Tree+> -->
  2806.  
  2807.  
  2808. <!-- ```python
  2809. Tree( data=None,
  2810. headings=None,
  2811. visible_column_map=None,
  2812. col_widths=None,
  2813. col0_width=10,
  2814. def_col_width=10,
  2815. auto_size_columns=True,
  2816. max_col_width=20,
  2817. select_mode=None,
  2818. show_expanded=False,
  2819. change_submits=False,
  2820. enable_events=False,
  2821. font=None,
  2822. justification='right',
  2823. text_color=None,
  2824. background_color=None,
  2825. num_rows=None,
  2826. row_height=None,
  2827. pad=None,
  2828. key=None,
  2829. tooltip=None,
  2830. right_click_menu=None,
  2831. visible=True)
  2832. ```
  2833. ```
  2834. class Tree(data=None - data in TreeData format
  2835. headings=None - list of strings representing your headings
  2836. visible_column_map=None - list of bools indicating which columns to display
  2837. col_widths=None - list of column widths
  2838. col0_width=10 - width of the first column which has the text data
  2839. def_col_width=10 - default column width
  2840. auto_size_columns=True - if true will autosize columns (currenly only sizes to col heading width)
  2841. max_col_width=20 - max width for columns in characters
  2842. select_mode=None - not yet used
  2843. show_expanded - Bool - if True the tree will be fully expanded when shown
  2844. font=None - the display font
  2845. justification='right' - justification for data display
  2846. text_color=None- color of text to display
  2847. background_color=None - background color
  2848. num_rows=None - number of rows to display
  2849. row_height=None - height of rows in pixels
  2850. pad=None - element padding
  2851. key=None - key for element
  2852. tooltip=None - tooltip
  2853. ```
  2854. -->
  2855.  
  2856. Unlike Tables there is no standard format for trees. Thus the data structure passed to the Tree Element must be constructed. This is done using the TreeData class. The process is as follows:
  2857. * Get a TreeData Object
  2858. * "Insert" data into the tree
  2859. * Pass the filled in TreeData object to Tree Element
  2860.  
  2861. #### TreeData format
  2862. ```python
  2863. def TreeData()
  2864. def Insert(self, parent, key, text, values, icon=None)
  2865. ```
  2866.  
  2867. To "insert" data into the tree the TreeData method Insert is called.
  2868.  
  2869. `Insert(parent_key, key, display_text, values)`
  2870.  
  2871. To indicate insertion at the head of the tree, use a parent key of "". So, every top-level node in the tree will have a parent node = ""
  2872.  
  2873. This code creates a TreeData object and populates with 3 values
  2874. ```python
  2875. treedata = sg.TreeData()
  2876.  
  2877. treedata.Insert("", '_A_', 'A', [1,2,3])
  2878. treedata.Insert("", '_B_', 'B', [4,5,6])
  2879. treedata.Insert("_A_", '_A1_', 'A1', ['can','be','anything'])
  2880. ```
  2881.  
  2882. Note that you ***can*** use the same values for display_text and keys. The only thing you have to watch for is that you cannot repeat keys.
  2883.  
  2884. When Reading a window the Table Element will return a list of rows that are selected by the user. The list will be empty is no rows are selected.
  2885.  
  2886. #### Icons on Tree Entries
  2887.  
  2888. If you wish to show an icon next to a tree item, then you specify the icon in the call to `Insert`. You pass in a filename or a Base64 bytes string using the optional `icon` parameter.
  2889.  
  2890. Here is the result of showing an icon with a tree entry.
  2891.  
  2892. ![image](https://user-images.githubusercontent.com/13696193/51087270-2b561e80-171f-11e9-8260-6142ea9b1137.png)
  2893.  
  2894.  
  2895. ## Tab and Tab Group Elements
  2896.  
  2897. Tabs have been a part of PySimpleGUI since the initial release. However, the initial implementation applied tabs at the top level only. The entire window had to be tabbed. There with other limitations that came along with that implementation. That all changed in version 3.8.0 with the new elements - Tab and TabGroup. The old implementation of Tabs was removed in version 3.8.0 as well.
  2898.  
  2899. Tabs are another "Container Element". The other Container Elements include:
  2900. * Frame
  2901. * Column
  2902.  
  2903. You layout a Frame in exactly the same way as a Frame or Column elements, by passing in a list of elements.
  2904.  
  2905. How you place a Tab into a Window is different than Graph or Frame elements. You cannot place a tab directly into a Window's layout. It much first be placed into a TabGroup. The TabGroup can then be placed into the Window.
  2906.  
  2907. Let's look at this Window as an example:
  2908.  
  2909. ![tabbed 1](https://user-images.githubusercontent.com/13696193/45992808-b10f6a80-c059-11e8-9746-ac71afd4d3d6.jpg)
  2910.  
  2911. View of second tab:
  2912.  
  2913. ![tabbed 2](https://user-images.githubusercontent.com/13696193/45992809-b10f6a80-c059-11e8-94e6-3bf543c9b0bd.jpg)
  2914.  
  2915.  
  2916. First we have the Tab layout definitions. They mirror what you see in the screen shots. Tab 1 has 1 Text Element in it. Tab 2 has a Text and an Input Element.
  2917.  
  2918.  
  2919. tab1_layout = [[sg.T('This is inside tab 1')]]
  2920.  
  2921. tab2_layout = [[sg.T('This is inside tab 2')],
  2922. [sg.In(key='in')]]
  2923.  
  2924. The layout for the entire window looks like this:
  2925.  
  2926. layout = [[sg.TabGroup([[sg.Tab('Tab 1', tab1_layout), sg.Tab('Tab 2', tab2_layout)]])],
  2927. [sg.RButton('Read')]]
  2928.  
  2929. The Window layout has the TabGroup and within the tab Group are the two Tab elements.
  2930.  
  2931. One important thing to notice about all of these container Elements... they all take a "list of lists" at the layout. They all have a layout that starts with `[[`
  2932.  
  2933. You will want to keep this `[[ ]]` construct in your head a you're debugging your tabbed windows. It's easy to overlook one or two necessary ['s
  2934.  
  2935. As mentioned earlier, the old-style Tabs were limited to being at the Window-level only. In other words, the tabs were equal in size to the entire window. This is not the case with the "new-style" tabs. This is why you're not going to be upset when you discover your old code no longer works with the new PySimpleGUI release. It'll be worth the few moments it'll take to convert your code.
  2936.  
  2937. Check out what's possible with the NEW Tabs!
  2938.  
  2939. ![tabs tabs tabs](https://user-images.githubusercontent.com/13696193/45993438-fd0fde80-c05c-11e8-9ed0-742f14d3070f.jpg)
  2940.  
  2941.  
  2942. Check out Tabs 7 and 8. We've got a Window with a Column containing Tabs 5 and 6. On Tab 6 are... Tabs 7 and 8.
  2943.  
  2944. As of Release 3.8.0, not all of *options* shown in the API definitions of the Tab and TabGroup Elements are working. They are there as placeholders.
  2945.  
  2946. The definition of a TabGroup is
  2947.  
  2948. TabGroup(layout,
  2949. title_color=None
  2950. background_color=None
  2951. font=None
  2952. pad=None
  2953. border_width=None
  2954. change_submits = False
  2955. key=None
  2956. tooltip=None)
  2957.  
  2958. The definition of a Tab Element is
  2959.  
  2960. Tab(title,
  2961. layout,
  2962. title_color=None,
  2963. background_color=None,
  2964. font=None,
  2965. pad=None
  2966. disabled=False
  2967. border_width=None
  2968. key=None
  2969. tooltip=None)
  2970.  
  2971.  
  2972. ### Reading Tab Groups
  2973.  
  2974. Tab Groups now return a value when a Read returns. They return which tab is currently selected. There is also a change_submits parameter that can be set that causes a Read to return if a Tab in that group is selected / changed. The key or title belonging to the Tab that was switched to will be returned as the value
  2975.  
  2976.  
  2977. ### Tab Element Methods
  2978. ```python
  2979. Update(disabled = None, visible=None)
  2980. ```
  2981. WARNING - This Update method may not be working correctly
  2982.  
  2983. <!-- %!% -->
  2984. ## Pane Element
  2985.  
  2986. New in version 3.20 is the Pane Element, a super-cool tkinter feature. You won't find this one in PySimpleGUIQt, only PySimpleGUI. It's difficult to describe one of these things. Think of them as "Tabs without labels" that you can slide.
  2987.  
  2988. ![pane3](https://user-images.githubusercontent.com/13696193/50035040-fcd50e80-ffcd-11e8-939c-df8ab8d64712.gif)
  2989.  
  2990. <!-- <+Pane+> -->
  2991.  
  2992. <!--
  2993. ```python
  2994.  
  2995. Pane(pane_list, background_color=None, size=(None, None), pad=None, orientation='vertical', show_handle=True, relief=RELIEF_RAISED, handle_size=None, border_width=None, key=None, visible=True):
  2996. ``` -->
  2997.  
  2998. ***Each "Pane" of a Pane Element must be a Column Element***. The parameter `pane_list` is a list of Column Elements.
  2999.  
  3000. Calls can get a little hairy looking if you try to declare everything in-line as you can see in this example.
  3001.  
  3002. ```python
  3003. sg.Pane([col5, sg.Column([[sg.Pane([col1, col2, col4], handle_size=15, orientation='v', background_color=None, show_handle=True, visible=True, key='_PANE_', border_width=0, relief=sg.RELIEF_GROOVE),]]),col3 ], orientation='h', background_color=None, size=(160,160), relief=sg.RELIEF_RAISED, border_width=0)
  3004. ```
  3005.  
  3006. Combing these with *visibility* make for an interesting interface with entire panes being hidden from view until neded by the user. It's one way of producing "dynamic" windows.
  3007.  
  3008.  
  3009. ## Colors
  3010. Starting in version 2.5 you can change the background colors for the window and the Elements.
  3011.  
  3012. Your windows can go from this:
  3013.  
  3014. ![snap0155](https://user-images.githubusercontent.com/13696193/43273879-a9fdc10a-90cb-11e8-8c20-4f6a244ebe2f.jpg)
  3015.  
  3016.  
  3017. to this... with one function call...
  3018.  
  3019.  
  3020. ![snap0156](https://user-images.githubusercontent.com/13696193/43273880-aa1955e6-90cb-11e8-94b6-673ecdb2698c.jpg)
  3021.  
  3022.  
  3023.  
  3024. While you can do it on an element by element or window level basis, the easiest way, by far, is a call to `SetOptions`.
  3025.  
  3026. Be aware that once you change these options they are changed for the rest of your program's execution. All of your windows will have that look and feel, until you change it to something else (which could be the system default colors.
  3027.  
  3028. This call sets all of the different color options.
  3029.  
  3030. SetOptions(background_color='#9FB8AD',
  3031. text_element_background_color='#9FB8AD',
  3032. element_background_color='#9FB8AD',
  3033. scrollbar_color=None,
  3034. input_elements_background_color='#F7F3EC',
  3035. progress_meter_color = ('green', 'blue')
  3036. button_color=('white','#475841'))
  3037.  
  3038. # SystemTray
  3039.  
  3040. This is a PySimpleGUIQt and PySimpleGUIWx only feature. Don't know of a way to do it using tkinter. Your source code for SystemTray is identical for the Qt and Wx implementations. You can switch frameworks by simply changing your import statement.
  3041.  
  3042. In addition to running normal windows, it's now also possible to have an icon down in the system tray that you can read to get menu events. There is a new SystemTray object that is used much like a Window object. You first get one, then you perform Reads in order to get events.
  3043.  
  3044. Here is the definition of the SystemTray object.
  3045.  
  3046. ```python
  3047. SystemTray(menu=None, filename=None, data=None, data_base64=None, tooltip=None):
  3048. '''
  3049. SystemTray - create an icon in the system tray
  3050. :param menu: Menu definition
  3051. :param filename: filename for icon
  3052. :param data: in-ram image for icon
  3053. :param data_base64: basee-64 data for icon
  3054. :param tooltip: tooltip string '''
  3055. ```
  3056.  
  3057. You'll notice that there are 3 different ways to specify the icon image. The base-64 parameter allows you to define a variable in your .py code that is the encoded image so that you do not need any additional files. Very handy feature.
  3058.  
  3059. ## System Tray Design Pattern
  3060.  
  3061. Here is a design pattern you can use to get a jump-start.
  3062.  
  3063. This program will create a system tray icon and perform a blocking Read. If the item "Open" is chosen from the system tray, then a popup is shown.
  3064.  
  3065. ```python
  3066. import PySimpleGUIQt as sg
  3067.  
  3068. menu_def = ['BLANK', ['&Open', '---', '&Save', ['1', '2', ['a', 'b']], '&Properties', 'E&xit']]
  3069.  
  3070. tray = sg.SystemTray(menu=menu_def, filename=r'default_icon.ico')
  3071.  
  3072. while True: # The event loop
  3073. menu_item = tray.Read()
  3074. print(menu_item)
  3075. if menu_item == 'Exit':
  3076. break
  3077. elif menu_item == 'Open':
  3078. sg.Popup('Menu item chosen', menu_item)
  3079.  
  3080. ```
  3081. The design pattern creates an icon that will display this menu:
  3082. ![snag-0293](https://user-images.githubusercontent.com/13696193/49057441-8bbfe980-f1cd-11e8-93e7-1aeda9ccd173.jpg)
  3083.  
  3084. ### Icons
  3085.  
  3086. When specifying "icons", you can use 3 different formats.
  3087. * `filename`- filename
  3088. * `data_base64` - base64 byte string
  3089. * '`data` - in-ram bitmap or other "raw" image
  3090.  
  3091. You will find 3 parameters used to specify these 3 options on both the initialize statement and on the Update method.
  3092.  
  3093. ## Menu Definition
  3094. ```python
  3095. menu_def = ['BLANK', ['&Open', '&Save', ['1', '2', ['a', 'b']], '!&Properties', 'E&xit']]
  3096. ```
  3097.  
  3098. A menu is defined using a list. A "Menu entry" is a string that specifies:
  3099. * text shown
  3100. * keyboard shortcut
  3101. * key
  3102.  
  3103. See section on Menu Keys for more information on using keys with menus.
  3104.  
  3105. An entry without a key and keyboard shortcut is a simple string
  3106. `'Menu Item'`
  3107.  
  3108. If you want to make the "M" be a keyboard shortcut, place an `&` in front of the letter that is the shortcut.
  3109. `'&Menu Item'`
  3110.  
  3111. You can add "keys" to make menu items unique or as another way of identifying a menu item than the text shown. The key is added to the text portion by placing `::` after the text.
  3112.  
  3113. `'Menu Item::key'`
  3114.  
  3115. The first entry can be ignored.`'BLANK`' was chosen for this example. It's this way because normally you would specify these menus under some heading on a menu-bar. But here there is no heading so it's filled in with any value you want.
  3116.  
  3117. **Separators**
  3118. If you want a separator between 2 items, add the entry `'---'` and it will add a separator item at that place in your menu.
  3119.  
  3120. **Disabled menu entries**
  3121.  
  3122. If you want to disable a menu entry, place a `!` before the menu entry
  3123.  
  3124.  
  3125. ## SystemTray Methods
  3126.  
  3127. ### Read - Read the context menu or check for events
  3128.  
  3129. ```python
  3130. def Read(timeout=None)
  3131. '''
  3132. Reads the context menu
  3133. :param timeout: Optional. Any value other than None indicates a non-blocking read
  3134. :return: String representing meny item chosen. None if nothing read.
  3135. '''
  3136. ```
  3137. The `timeout` parameter specifies how long to wait for an event to take place. If nothing happens within the timeout period, then a "timeout event" is returned. These types of reads make it possible to run asynchronously. To run non-blocked, specify `timeout=0`on the Read call.
  3138.  
  3139. Read returns the menu text, complete with key, for the menu item chosen. If you specified `Open::key` as the menu entry, and the user clicked on `Open`, then you will receive the string `Open::key` upon completion of the Read.
  3140.  
  3141. #### Read special return values
  3142.  
  3143. In addition to Menu Items, the Read call can return several special values. They include:
  3144.  
  3145. EVENT_SYSTEM_TRAY_ICON_DOUBLE_CLICKED - Tray icon was double clicked
  3146. EVENT_SYSTEM_TRAY_ICON_ACTIVATED - Tray icon was single clicked
  3147. EVENT_SYSTEM_TRAY_MESSAGE_CLICKED - a message balloon was clicked
  3148. TIMEOUT_KEY is returned if no events are available if the timeout value is set in the Read call
  3149.  
  3150.  
  3151. ### Hide
  3152.  
  3153. Hides the icon. Note that no message balloons are shown while an icon is hidden.
  3154.  
  3155. ```python
  3156. def Hide()
  3157. ```
  3158.  
  3159. ### Close
  3160.  
  3161. Does the same thing as hide
  3162. ```python
  3163. def Close()
  3164. ```
  3165.  
  3166.  
  3167. ### UnHide
  3168.  
  3169. Shows a previously hidden icon
  3170.  
  3171. ```python
  3172. def UnHide()
  3173. ```
  3174.  
  3175. ### ShowMessage
  3176.  
  3177. Shows a balloon above the icon in the system tray area. You can specify your own icon to be shown in the balloon, or you can set `messageicon` to one of the preset values.
  3178.  
  3179. This message has a custom icon.
  3180.  
  3181. ![snag-0286](https://user-images.githubusercontent.com/13696193/49057459-a85c2180-f1cd-11e8-9a66-aa331d7e034c.jpg)
  3182.  
  3183. The preset `messageicon` values are:
  3184.  
  3185. SYSTEM_TRAY_MESSAGE_ICON_INFORMATION
  3186. SYSTEM_TRAY_MESSAGE_ICON_WARNING
  3187. SYSTEM_TRAY_MESSAGE_ICON_CRITICAL
  3188. SYSTEM_TRAY_MESSAGE_ICON_NOICON
  3189.  
  3190. ```python
  3191. ShowMessage(title, message, filename=None, data=None, data_base64=None, messageicon=None, time=10000):
  3192. '''
  3193. Shows a balloon above icon in system tray
  3194. :param title: Title shown in balloon
  3195. :param message: Message to be displayed
  3196. :param filename: Optional icon filename
  3197. :param data: Optional in-ram icon
  3198. :param data_base64: Optional base64 icon
  3199. :param time: How long to display message in milliseconds :return:
  3200. '''
  3201. ```
  3202. Note, on windows it may be necessary to make a registry change to enable message balloons to be seen. To fix this, you must create the DWORD you see in this screenshot.
  3203.  
  3204. ![snag-0285](https://user-images.githubusercontent.com/13696193/49056144-6381bc00-f1c8-11e8-9f44-199394823369.jpg)
  3205.  
  3206.  
  3207. ### Update
  3208.  
  3209. You can update any of these items within a SystemTray object
  3210. * Menu definition
  3211. * Icon
  3212. * Tooltip
  3213.  
  3214. Change them all or just 1.
  3215.  
  3216. ```python
  3217. Update(menu=None, tooltip=None,filename=None, data=None, data_base64=None,)
  3218. '''
  3219. Updates the menu, tooltip or icon
  3220. :param menu: menu defintion
  3221. :param tooltip: string representing tooltip
  3222. :param filename: icon filename
  3223. :param data: icon raw image
  3224. :param data_base64: icon base 64 image
  3225. :return:
  3226. '''
  3227. ```
  3228.  
  3229.  
  3230. # Global Settings
  3231. **Global Settings**
  3232. Let's have some fun customizing! Make PySimpleGUI look the way you want it to look. You can set the global settings using the function `PySimpleGUI.SetOptions`. Each option has an optional parameter that's used to set it.
  3233.  
  3234. SetOptions(icon=None
  3235. button_color=(None,None)
  3236. element_size=(None,None),
  3237. margins=(None,None),
  3238. element_padding=(None,None)
  3239. auto_size_text=None
  3240. auto_size_buttons=None
  3241. font=None
  3242. border_width=None
  3243. slider_border_width=None
  3244. slider_relief=None
  3245. slider_orientation=None
  3246. autoclose_time=None
  3247. message_box_line_width=None
  3248. progress_meter_border_depth=None
  3249. progress_meter_style=None
  3250. progress_meter_relief=None
  3251. progress_meter_color=None
  3252. progress_meter_size=None
  3253. text_justification=None
  3254. text_color=None
  3255. background_color=None
  3256. element_background_color=None
  3257. text_element_background_color=None
  3258. input_elements_background_color=None
  3259. element_text_color=None
  3260. input_text_color=None
  3261. scrollbar_color=None, text_color=None
  3262. debug_win_size=(None,None)
  3263. window_location=(None,None)
  3264. tooltip_time = None
  3265.  
  3266. Explanation of parameters
  3267.  
  3268. icon - filename of icon used for taskbar and title bar
  3269. button_color - button color (foreground, background)
  3270. element_size - element size (width, height) in characters
  3271. margins - tkinter margins around outsize
  3272. element_padding - tkinter padding around each element
  3273. auto_size_text - autosize the elements to fit their text
  3274. auto_size_buttons - autosize the buttons to fit their text
  3275. font - font used for elements
  3276. border_width - amount of bezel or border around sunken or raised elements
  3277. slider_border_width - changes the way sliders look
  3278. slider_relief - changes the way sliders look
  3279. slider_orientation - changes orientation of slider
  3280. autoclose_time - time in seconds for autoclose boxes
  3281. message_box_line_width - number of characers in a line of text in message boxes
  3282. progress_meter_border_depth - amount of border around raised or lowered progress meters
  3283. progress_meter_style - style of progress meter as defined by tkinter
  3284. progress_meter_relief - relief style
  3285. progress_meter_color - color of the bar and background of progress meters
  3286. progress_meter_size - size in (characters, pixels)
  3287. background_color - Color of the main window's background
  3288. element_background_color - Background color of the elements
  3289. text_element_background_color - Text element background color
  3290. input_elements_background_color - Input fields background color
  3291. element_text_color - Text color of elements that have text, like Radio Buttons
  3292. input_text_color - Color of the text that you type in
  3293. scrollbar_color - Color for scrollbars (may not always work)
  3294. text_color - Text element default text color
  3295. text_justification - justification to use on Text Elements. Values are strings - 'left', 'right', 'center'
  3296. debug_win_size - size of the Print output window
  3297. window_location - location on the screen (x,y) of window's top left cornder
  3298. tooltip_time - time in milliseconds to wait before showing a tooltip. Default is 400ms
  3299.  
  3300.  
  3301. These settings apply to all windows `SetOptions`. The Row options and Element options will take precedence over these settings. Settings can be thought of as levels of settings with the window-level being the highest and the Element-level the lowest. Thus the levels are:
  3302.  
  3303. - window level
  3304. - Row level
  3305. - Element level
  3306.  
  3307. Each lower level overrides the settings of the higher level. Once settings have been changed, they remain changed for the duration of the program (unless changed again).
  3308.  
  3309. # Persistent windows (Window stays open after button click)
  3310.  
  3311. Apologies that the next few pages are perhaps confusing. There have been a number of changes recently in PySimpleGUI's Read calls that added some really cool stuff, but at the expense of being not so simple. Part of the issue is an attempt to make sure existing code doesn't break. These changes are all in the area of non-blocking reads and reads with timeouts.
  3312.  
  3313. There are 2 ways to keep a window open after the user has clicked a button. One way is to use non-blocking windows (see the next section). The other way is to use buttons that 'read' the window instead of 'close' the window when clicked. The typical buttons you find in windows, including the shortcut buttons, close the window. These include OK, Cancel, Submit, etc. The Button Element also closes the window.
  3314.  
  3315. The `RButton` Element creates a button that when clicked will return control to the user, but will leave the window open and visible. This button is also used in Non-Blocking windows. The difference is in which call is made to read the window. The normal `Read` call with no parameters will block, a call with a `timeout` value of zero will not block.
  3316.  
  3317. Note that `InputText` and `MultiLine` Elements will be **cleared** when performing a `Read`. If you do not want your input field to be cleared after a `Read` then you can set the `do_not_clear` parameter to True when creating those elements. The clear is turned on and off on an element by element basis.
  3318.  
  3319. The reasoning behind this is that Persistent Windows are often "forms". When "submitting" a form you want to have all of the fields left blank so the next entry of data will start with a fresh window. Also, when implementing a "Chat Window" type of interface, after each read / send of the chat data, you want the input field cleared. Think of it as a Texting application. Would you want to have to clear your previous text if you want to send a second text?
  3320.  
  3321. The design pattern for Persistent Windows was already shown to you earlier in the document... here it is for your convenience.
  3322.  
  3323. ```python
  3324. import PySimpleGUI as sg
  3325.  
  3326. layout = [[sg.Text('Persistent window')],
  3327. [sg.Input()],
  3328. [sg.RButton('Read'), sg.Exit()]]
  3329.  
  3330. window = sg.Window('Window that stays open').Layout(layout)
  3331.  
  3332. while True:
  3333. event, values = window.Read()
  3334. if event is None or event == 'Exit':
  3335. break
  3336. print(event, values)
  3337.  
  3338. window.Close()
  3339. ```
  3340.  
  3341.  
  3342. ## Read(timeout = t, timeout_key='timeout')
  3343.  
  3344. Read with a timeout is a very good thing for your GUIs to use in a read non-blocking situation, if you can use them. If your device can wait for a little while, then use this kind of read. The longer you're able to add to the timeout value, the less CPU time you'll be taking.
  3345.  
  3346. One way of thinking of reads with timeouts:
  3347. > During the timeout time, you are "yielding" the processor to do other tasks.
  3348.  
  3349. But it gets better than just being a good citizen....**your GUI will be more responsive than if you used a non-blocking read**
  3350.  
  3351. Let's say you had a device that you want to "poll" every 100ms. The "easy way out" and the only way out until recently was this:
  3352.  
  3353. ```python
  3354. # YOU SHOULD NOT DO THIS....
  3355. while True: # Event Loop
  3356. event, values = window.ReadNonBlocking() # DO NOT USE THIS CALL ANYMORE
  3357. read_my_hardware() # process my device here
  3358. time.sleep(.1) # sleep 1/10 second
  3359. ```
  3360.  
  3361. This program will quickly test for user input, then deal with the hardware. Then it'll sleep for 100ms, while your gui is non-responsive, then it'll check in with your GUI again. I fully realize this is a crude way of doing things. We're talking dirt simple stuff without trying to use threads, etc to 'get it right'. It's for demonstration purposes.
  3362.  
  3363. The new and better way....
  3364. using the Read Timeout mechanism, the sleep goes away.
  3365.  
  3366. ```python
  3367. # This is the right way to poll for hardware
  3368. while True: # Event Loop
  3369. event, values = window.Read(timeout = 100)
  3370. read_my_hardware() # process my device here
  3371. ```
  3372.  
  3373. This event loop will run every 100 ms. You're making a Read call, so anything that the use does will return back to you immediately, and you're waiting up to 100ms for the user to do something. If the user doesn't do anything, then the read will timeout and execution will return to the program.
  3374.  
  3375.  
  3376. ## Non-Blocking Windows (Asynchronous reads)
  3377.  
  3378. There are TWO ways to perform a non-blocking read.
  3379.  
  3380. The "old way" was:
  3381. ```python
  3382. event, values = sg.ReadNonBlocking()
  3383. ```
  3384. The new way
  3385. ```python
  3386. event, values = sg.Read(timeout=0)
  3387. ```
  3388. You should use the new way if you're reading this for the first time.
  3389.  
  3390. The difference in the 2 calls is in the value of event. For ReadNonBlocking, event will be `None` if there are no other events to report. There is a "problem" with this however. With normal Read calls, an event value of None signified the window was closed. For ReadNonBlocking, the way a closed window is returned is via the values variable being set to None.
  3391.  
  3392.  
  3393. ## sg.TIMEOUT_KEY
  3394.  
  3395. If you're using the new, timeout=0 method, then an event value of None signifies that the window was closed, just like a normal Read. That leaves the question of what it is set to when not other events are happening. This value will be the value of `timeout_key`. If you did not specify a timeout_key value in your call to read, then it will be set to a default value of:
  3396. TIMEOUT_KEY = '__timeout__'
  3397.  
  3398. If you wanted to test for "no event" in your loop, it would be written like this:
  3399. ```python
  3400. while True:
  3401. event, value = window.Read(timeout=0)
  3402. if event is None:
  3403. break # the use has closed the window
  3404. if event == sg.TIMEOUT_KEY:
  3405. print("Nothing happened")
  3406. ```
  3407.  
  3408.  
  3409. Use async windows sparingly. It's possible to have a window that appears to be async, but it is not. **Please** try to find other methods before going to async windows. The reason for this plea is that async windows poll tkinter over and over. If you do not have a sleep in your loop, you will eat up 100% of the CPU time. It's important to be a good citizen. Don't chew up CPU cycles needlessly.
  3410.  
  3411. Non-blocking is generally reserved as a "last resort". Too many times people use non-blocking reads when a blocking read will do just fine.
  3412.  
  3413. There is a hybrid approach... a read with a timeout. You'll score much higher points on the impressive meter if you're able to use a lot less CPU time by using this type of read.
  3414.  
  3415. The most legit time to use a non-blocking window is when you're working directly with hardware. Maybe you're driving a serial bus. If you look at the Event Loop in the Demo_OpenCV_Webcam.py program, you'll see that the read is a non-blocking read. However, there is a place in the event loop where blocking occurs. The point in the loop where you will block is the call to read frames from the webcam. When a frame is available you want to quickly deliver it to the output device, so you don't want your GUI blocking. You want the read from the hardware to block.
  3416.  
  3417. Another example can be found in the demo for controlling a robot on a Raspberry Pi. In that application you want to read the direction buttons, forward, backward, etc, and immediately take action. If you are using RealtimeButtons, your only option at the moment is to use non-blocking windows. You have to set the timeout to zero if you want the buttons to be real-time responsive.
  3418.  
  3419. However, with these buttons, adding a sleep to your event loop will at least give other processes time to execute. It will, however, starve your GUI. The entire time you're sleeping, your GUI isn't executing.
  3420.  
  3421.  
  3422. ### Periodically Calling`Read`
  3423.  
  3424. Let's say you do end up using non-blocking reads... then you've got some housekeeping to do. It's up to you to periodically "refresh" the visible GUI. The longer you wait between updates to your GUI the more sluggish your windows will feel. It is up to you to make these calls or your GUI will freeze.
  3425.  
  3426. There are 2 methods of interacting with non-blocking windows.
  3427. 1. Read the window just as you would a normal window
  3428. 2. "Refresh" the window's values without reading the window. It's a quick operation meant to show the user the latest values
  3429.  
  3430. With asynchronous windows the window is shown, user input is read, but your code keeps right on chugging. YOUR responsibility is to call `PySimpleGUI.Read` on a periodic basis. Several times a second or more will produce a reasonably snappy GUI.
  3431.  
  3432. ## Exiting (Closing) a Persistent Window
  3433.  
  3434. If your window has a button that closes the window, then PySimpleGUI will automatically close the window for you. If all of your buttons are ReadButtons, then it'll be up to you to close the window when done.
  3435. To close a window, call the `Close` method.
  3436. ```python
  3437. window.Close()
  3438. ```
  3439.  
  3440. ## Persistent Window Example - Running timer that updates
  3441.  
  3442. See the sample code on the GitHub named Demo Media Player for another example of Async windows. We're going to make a window and update one of the elements of that window every .01 seconds. Here's the entire code to do that.
  3443.  
  3444. ```python
  3445. import PySimpleGUI as sg
  3446. import time
  3447.  
  3448. # ---------------- Create Form ----------------
  3449. sg.ChangeLookAndFeel('Black')
  3450. sg.SetOptions(element_padding=(0, 0))
  3451.  
  3452. layout = [[sg.Text('')],
  3453. [sg.Text('', size=(8, 2), font=('Helvetica', 20), justification='center', key='text')],
  3454. [sg.ReadButton('Pause', key='button', button_color=('white', '#001480')),
  3455. sg.ReadButton('Reset', button_color=('white', '#007339'), key='Reset'),
  3456. sg.Exit(button_color=('white', 'firebrick4'), key='Exit')]]
  3457.  
  3458. window = sg.Window('Running Timer', no_titlebar=True, auto_size_buttons=False, keep_on_top=True, grab_anywhere=True).Layout(layout)
  3459.  
  3460. # ---------------- main loop ----------------
  3461. current_time = 0
  3462. paused = False
  3463. start_time = int(round(time.time() * 100))
  3464. while (True):
  3465. # --------- Read and update window --------
  3466. event, values = window.Read(timeout=10)
  3467. current_time = int(round(time.time() * 100)) - start_time
  3468. # --------- Display timer in window --------
  3469. window.FindElement('text').Update('{:02d}:{:02d}.{:02d}'.format((current_time // 100) // 60,
  3470. (current_time // 100) % 60,
  3471. current_time % 100))
  3472. ```
  3473.  
  3474.  
  3475. Previously this program was implemented using a sleep in the loop to control the clock tick. This version uses the new timeout parameter. The result is a window that reacts quicker then the one with the sleep and the accuracy is just as good.
  3476.  
  3477.  
  3478. ## Instead of a Non-blocking Read --- Use `change_submits = True` or return_keyboard_events = True
  3479.  
  3480. Any time you are thinking "I want an X Element to cause a Y Element to do something", then you want to use the `change_submits` option.
  3481.  
  3482. ***Instead of polling, try options that cause the window to return to you.*** By using non-blocking windows, you are *polling*. You can indeed create your application by polling. It will work. But you're going to be maxing out your processor and may even take longer to react to an event than if you used another technique.
  3483.  
  3484. **Examples**
  3485.  
  3486. One example is you have an input field that changes as you press buttons on an on-screen keypad.
  3487.  
  3488. ![keypad 3](https://user-images.githubusercontent.com/13696193/45260275-a2198e80-b3b0-11e8-85fe-a4ce6484510f.jpg)
  3489.  
  3490.  
  3491.  
  3492.  
  3493. # Updating Elements (changing elements in active window)
  3494.  
  3495. If you want to change Elements in your window after the window has been created, then you will call the Element's Update method.
  3496.  
  3497. **NOTE** a window **must be Read or Finalized** before any Update calls can be made.
  3498.  
  3499. Here is an example of updating a Text Element
  3500.  
  3501. ```python
  3502. import PySimpleGUI as sg
  3503.  
  3504. layout = [ [sg.Text('My layout', key='_TEXT_')],
  3505. [sg.Button('Read')]]
  3506.  
  3507. window = sg.Window('My new window').Layout(layout)
  3508.  
  3509. while True: # Event Loop
  3510. event, values = window.Read()
  3511. if event is None:
  3512. break
  3513. window.Element('_TEXT_').Update('My new text value')
  3514. ```
  3515.  
  3516. Notice the placement of the Update call. If you wanted to Update the Text Element *prior* to the Read call, outside of the event loop, then you must call Finalize on the window first.
  3517.  
  3518. In this example, the Update is done prior the Read. Because of this, the Finalize call is added to the Window creation.
  3519. ```python
  3520. import PySimpleGUI as sg
  3521.  
  3522. layout = [ [sg.Text('My layout', key='_TEXT_')],
  3523. [sg.Button('Read')]
  3524. ]
  3525.  
  3526. window = sg.Window('My new window').Layout(layout).Finalize()
  3527.  
  3528. window.Element('_TEXT_').Update('My new text value')
  3529.  
  3530. while True: # Event Loop
  3531. event, values = window.Read()
  3532. if event is None:
  3533. break
  3534. ```
  3535.  
  3536.  
  3537. Persistent windows remain open and thus continue to interact with the user after the Read has returned. Often the program wishes to communicate results (output information) or change an Element's values (such as populating a List Element).
  3538.  
  3539. You can use Update to do things like:
  3540. * Have one Element (appear to) make a change to another Element
  3541. * Disable a button, slider, input field, etc
  3542. * Change a button's text
  3543. * Change an Element's text or background color
  3544. * Add text to a scrolling output window
  3545. * Change the choices in a list
  3546. * etc
  3547.  
  3548. The way this is done is via an Update method that is available for nearly all of the Elements. Here is an example of a program that uses a persistent window that is updated.
  3549.  
  3550. ![snap0272](https://user-images.githubusercontent.com/13696193/45260249-ec4e4000-b3af-11e8-853b-9b29d0bf7797.jpg)
  3551.  
  3552.  
  3553. In some programs these updates happen in response to another Element. This program takes a Spinner and a Slider's input values and uses them to resize a Text Element. The Spinner and Slider are on the left, the Text element being changed is on the right.
  3554.  
  3555.  
  3556. # Testing async window, see if can have a slider
  3557. # that adjusts the size of text displayed
  3558.  
  3559. import PySimpleGUI as sg
  3560. fontSize = 12
  3561. layout = [[sg.Spin([sz for sz in range(6, 172)], font=('Helvetica 20'), initial_value=fontSize, change_submits=True, key='spin'),
  3562. sg.Slider(range=(6,172), orientation='h', size=(10,20),
  3563. change_submits=True, key='slider', font=('Helvetica 20')),
  3564. sg.Text("Aa", size=(2, 1), font="Helvetica " + str(fontSize), key='text')]]
  3565.  
  3566. sz = fontSize
  3567. window = sg.Window("Font size selector", grab_anywhere=False).Layout(layout)
  3568. # Event Loop
  3569. while True:
  3570. event, values= window.Read()
  3571. if event is None:
  3572. break
  3573. sz_spin = int(values['spin'])
  3574. sz_slider = int(values['slider'])
  3575. sz = sz_spin if sz_spin != fontSize else sz_slider
  3576. if sz != fontSize:
  3577. fontSize = sz
  3578. font = "Helvetica " + str(fontSize)
  3579. window.FindElement('text').Update(font=font)
  3580. window.FindElement('slider').Update(sz)
  3581. window.FindElement('spin').Update(sz)
  3582.  
  3583. print("Done.")
  3584.  
  3585.  
  3586. Inside the event loop we read the value of the Spinner and the Slider using those Elements' keys.
  3587. For example, `values['slider']` is the value of the Slider Element.
  3588.  
  3589. This program changes all 3 elements if either the Slider or the Spinner changes. This is done with these statements:
  3590.  
  3591. window.FindElement('text').Update(font=font)
  3592. window.FindElement('slider').Update(sz)
  3593. window.FindElement('spin').Update(sz)
  3594.  
  3595. Remember this design pattern because you will use it OFTEN if you use persistent windows.
  3596.  
  3597. It works as follows. The call to `window.FindElement` returns the Element object represented by they provided `key`. This element is then updated by calling it's `Update` method. This is another example of Python's "chaining" feature. We could write this code using the long-form:
  3598.  
  3599. text_element = window.FindElement('text')
  3600. text_element.Update(font=font)
  3601.  
  3602. The takeaway from this exercise is that keys are key in PySimpleGUI's design. They are used to both read the values of the window and also to identify elements. As already mentioned, they are used as targets in Button calls.
  3603.  
  3604. ### Locating Elements
  3605.  
  3606. The Window method call that's used to find an element is:
  3607. `FindElement`
  3608. or the shortened version
  3609. `Element`
  3610.  
  3611. When you see a call to window.FindElement or window.Element, then you know an element is being addressed. Normally this is done so you can call the element's Update method.
  3612.  
  3613.  
  3614. ### ProgressBar / Progress Meters
  3615.  
  3616. Note that to change a progress meter's progress, you call UpdateBar, not Update. It's an old naming convention that's left over from before the Update calls were implemented.
  3617.  
  3618.  
  3619.  
  3620. # Keyboard & Mouse Capture
  3621. Beginning in version 2.10 you can capture keyboard key presses and mouse scroll-wheel events. Keyboard keys can be used, for example, to detect the page-up and page-down keys for a PDF viewer. To use this feature, there's a boolean setting in the Window call `return_keyboard_events` that is set to True in order to get keys returned along with buttons.
  3622.  
  3623. Keys and scroll-wheel events are returned in exactly the same way as buttons.
  3624.  
  3625. For scroll-wheel events, if the mouse is scrolled up, then the `button` text will be `MouseWheel:Up`. For downward scrolling, the text returned is `MouseWheel:Down`
  3626.  
  3627. Keyboard keys return 2 types of key events. For "normal" keys (a,b,c, etc), a single character is returned that represents that key. Modifier and special keys are returned as a string with 2 parts:
  3628.  
  3629. Key Sym:Key Code
  3630.  
  3631. Key Sym is a string such as 'Control_L'. The Key Code is a numeric representation of that key. The left control key, when pressed will return the value 'Control_L:17'
  3632.  
  3633. import PySimpleGUI as sg
  3634.  
  3635. # Recipe for getting keys, one at a time as they are released
  3636. # If want to use the space bar, then be sure and disable the "default focus"
  3637.  
  3638. with sg.Window("Keyboard Test", return_keyboard_events=True, use_default_focus=False) as window:
  3639. text_elem = sg.Text("", size=(18, 1))
  3640. layout = [[sg.Text("Press a key or scroll mouse")],
  3641. [text_elem],
  3642. [sg.Button("OK")]]
  3643.  
  3644. window.Layout(layout)
  3645. # ---===--- Loop taking in user input --- #
  3646. while True:
  3647. event, value = window.Read()
  3648.  
  3649. if event == "OK" or event is None:
  3650. print(event, "exiting")
  3651. break
  3652. text_elem.Update(event)
  3653.  
  3654.  
  3655.  
  3656. You want to turn off the default focus so that there no buttons that will be selected should you press the spacebar.
  3657.  
  3658. ### Realtime Keyboard Capture
  3659. Use realtime keyboard capture by calling
  3660.  
  3661. import PySimpleGUI as sg
  3662.  
  3663. with sg.Window("Realtime Keyboard Test", return_keyboard_events=True, use_default_focus=False) as window:
  3664. layout = [[sg.Text("Hold down a key")],
  3665. [sg.Button("OK")]]
  3666.  
  3667. window.Layout(layout)
  3668.  
  3669. while True:
  3670. event, value = window.Read(timeout=0)
  3671. if event == "OK" or event is None:
  3672. print(event, value, "exiting")
  3673. break
  3674. if event != sg.TIMEOUT_KEY:
  3675. print(event)
  3676.  
  3677.  
  3678. # Menus
  3679.  
  3680. ## MenuBar
  3681.  
  3682. Beginning in version 3.01 you can add a MenuBar to your window. You specify the menus in much the same way as you do window layouts, with lists. Menu selections are returned as events and as of 3.17, also as in the values dictionary. The value returned will be the entire menu entry, including the key if you specified one.
  3683.  
  3684.  
  3685. This definition:
  3686.  
  3687. menu_def = [['File', ['Open', 'Save', 'Exit',]],
  3688. ['Edit', ['Paste', ['Special', 'Normal',], 'Undo'],],
  3689. ['Help', 'About...'],]
  3690.  
  3691. Note the placement of ',' and of []. It's tricky to get the nested menus correct that implement cascading menus. See how paste has Special and Normal as a list after it. This means that Paste has a cascading menu with items Special and Normal.
  3692.  
  3693. They menu_def layout produced this window:
  3694.  
  3695. ![menu](https://user-images.githubusercontent.com/13696193/45306723-56b7cb00-b4eb-11e8-8cbd-faef0c90f8b4.jpg)
  3696.  
  3697.  
  3698. To add a menu to a Window place the `Menu` or `MenuBar` element into your layout.
  3699.  
  3700. layout = [[sg.Menu(menu_def)]]
  3701.  
  3702. It doesn't really matter where you place the Menu Element in your layout as it will always be located at the top of the window.
  3703.  
  3704. ## ButtonMenus
  3705.  
  3706. Button menus were introduced in version 3.21, having been previously released in PySimpleGUIQt. They work exactly the same and are source code compatible between PySimpleGUI and PySimpleGUIQt. These types of menus take a single menu entry where a Menu Bar takes a list of menu entries.
  3707.  
  3708. ## Right Click Menus
  3709.  
  3710. Right Click Menus were introduced in version 3.21. Almost every element has a right_click_menu parameter and there is a window-level setting for rich click menu that will attach a right click menu to all elements in the window.
  3711.  
  3712. The menu definition is the same a s the button menu definition, a single menu entry.
  3713.  
  3714. ```python
  3715. right_click_menu = ['&Right', ['Right', '!&Click', '&Menu', 'E&xit', 'Properties']]
  3716. ```
  3717. The first string in a right click menu and a button menu is ***ignored***. It is not used. Normally you would put the string that is shown on the menu bar in that location.
  3718.  
  3719. **Return values for right click menus are different than menu bars and button menus.** Instead of the value being returned through the values dictionary, it is instead sent back as an Event. You will not
  3720.  
  3721. ## Menu Shortcut keys
  3722. You have used ALT-key in other Windows programs to navigate menus. For example Alt-F+X exits the program. The Alt-F pulls down the File menu. The X selects the entry marked Exit.
  3723.  
  3724. The good news is that PySimpleGUI allows you to create the same kind of menus! Your program can play with the big-boys. And, it's trivial to do.
  3725.  
  3726. All that's required is for your to add an "&" in front of the letter you want to appear with an underscore. When you hold the Alt key down you will see the menu with underlines that you marked.
  3727.  
  3728. One other little bit of polish you can add are separators in your list. To add a line in your list of menu choices, create a menu entry that looks like this: ` '---'`
  3729.  
  3730. This is an example Menu with underlines and a separator.
  3731.  
  3732. ```
  3733. # ------ Menu Definition ------ #
  3734. menu_def = [['&File', ['&Open', '&Save', '---', 'Properties', 'E&xit' ]],
  3735. ['&Edit', ['Paste', ['Special', 'Normal',], 'Undo'],],
  3736. ['&Help', '&About...'],]
  3737. ```
  3738. And this is the spiffy menu it produced:
  3739. ![menus with shortcuts](https://user-images.githubusercontent.com/13696193/46251674-f5b74f00-c427-11e8-95c6-547adc59041b.jpg)
  3740.  
  3741.  
  3742. ## Disabled Menu Entries
  3743.  
  3744. If you want one of your menu items to be disabled, then place a '!' in front of the menu entry. To disable the Paste menu entry in the previous examples, the entry would be:
  3745. `['!&Edit', ['Paste', ['Special', 'Normal',], 'Undo'],]`
  3746.  
  3747. If your want to change the disabled menu item flag / character from '!' to something else, change the variable `MENU_DISABLED_CHARACTER`
  3748.  
  3749. ## Keys for Menus
  3750.  
  3751. Beginning in version 3.17 you can add a `key` to your menu entries. The `key` value will be removed prior to be inserted into the menu. When you receive Menu events, the entire menu entry, including the `key` is returned. A key is indicated by adding `::` after a menu entry, followed by the key.
  3752.  
  3753. To add the `key` `_MY_KEY_` to the Special menu entry, the code would be:
  3754.  
  3755. `['&Edit', ['Paste', ['Special::_MY_KEY_', 'Normal',], 'Undo'],]`
  3756.  
  3757. If you want to change the characters that indicate a key follows from '::' to something else, change the variable `MENU_KEY_SEPARATOR`
  3758.  
  3759.  
  3760. # Running Multiple Windows
  3761.  
  3762. If you wish to run multiple windows in your event loop, then there are 2 methods for doing this.
  3763.  
  3764. 1. First window does not remain active while second window is visible
  3765. 2. First window remains active while second window is visible
  3766.  
  3767. You will find the 2 design matters in 2 demo programs in the Demo Program area of the GitHub (http://www.PySimpleGUI.com)
  3768.  
  3769. ***Critically important***
  3770. When creating a new window you must use a "fresh" layout every time. You cannot reuse a layout from a previous window. As a result you will see the layout for window 2 being defined inside of the larger event loop.
  3771.  
  3772. A rule of thumb to follow:
  3773.  
  3774. > If you are calling `Window` then you should define your window layout
  3775. > in the statement just prior to the `Window` call.
  3776.  
  3777.  
  3778. ## Multi-Window Design Pattern 1 - both windows active
  3779.  
  3780. ```python
  3781. import PySimpleGUI as sg
  3782.  
  3783. # Design pattern 2 - First window remains active
  3784.  
  3785. layout = [[ sg.Text('Window 1'),],
  3786. [sg.Input(do_not_clear=True)],
  3787. [sg.Text('', key='_OUTPUT_')],
  3788. [sg.Button('Launch 2'), sg.Button('Exit')]]
  3789.  
  3790. win1 = sg.Window('Window 1').Layout(layout)
  3791.  
  3792. win2_active = False
  3793. while True:
  3794. ev1, vals1 = win1.Read(timeout=100)
  3795. win1.FindElement('_OUTPUT_').Update(vals1[0])
  3796. if ev1 is None or ev1 == 'Exit':
  3797. break
  3798.  
  3799. if not win2_active and ev1 == 'Launch 2':
  3800. win2_active = True
  3801. layout2 = [[sg.Text('Window 2')],
  3802. [sg.Button('Exit')]]
  3803.  
  3804. win2 = sg.Window('Window 2').Layout(layout2)
  3805.  
  3806. if win2_active:
  3807. ev2, vals2 = win2.Read(timeout=100)
  3808. if ev2 is None or ev2 == 'Exit':
  3809. win2_active = False
  3810. win2.Close()
  3811. ```
  3812.  
  3813.  
  3814. ## Multi-Window Design Pattern 2 - only 1 active window
  3815.  
  3816. ```python
  3817. import PySimpleGUIQt as sg
  3818.  
  3819. # Design pattern 1 - First window does not remain active
  3820.  
  3821. layout = [[ sg.Text('Window 1'),],
  3822. [sg.Input(do_not_clear=True)],
  3823. [sg.Text('', key='_OUTPUT_')],
  3824. [sg.Button('Launch 2')]]
  3825.  
  3826. win1 = sg.Window('Window 1').Layout(layout)
  3827. win2_active=False
  3828. while True:
  3829. ev1, vals1 = win1.Read(timeout=100)
  3830. if ev1 is None:
  3831. break
  3832. win1.FindElement('_OUTPUT_').Update(vals1[0])
  3833.  
  3834. if ev1 == 'Launch 2' and not win2_active:
  3835. win2_active = True
  3836. win1.Hide()
  3837. layout2 = [[sg.Text('Window 2')], # note must create a layout from scratch every time. No reuse
  3838. [sg.Button('Exit')]]
  3839.  
  3840. win2 = sg.Window('Window 2').Layout(layout2)
  3841. while True:
  3842. ev2, vals2 = win2.Read()
  3843. if ev2 is None or ev2 == 'Exit':
  3844. win2.Close()
  3845. win2_active = False
  3846. win1.UnHide()
  3847. break
  3848. ```
Add Comment
Please, Sign In to add comment