Easygui Learning Document "Super-detailed Chinese version"

Source: Internet
Author: User
Tags stack trace

Translation adapted from official documents: http://easygui.sourceforge.net/tutorial/index.html

Translated by: Small turtle, this article welcome reprint, reproduced please ensure the integrity of the original!

Demo using Python version 3.3.3


0. installing Easygui

Official website: http://easygui.sourceforge.net

Latest Version: Easygui-0.96.zip (141.61 KB, download number: 1265)

Install using the standard method:


    1. Use the command window to switch to the easygui-docs-0.96 directory
    2. "Under Windows" execution C:\Python33\python.exe setup.py Install
    3. "Linux or Mac" sudo/usr/bin/python33 setup.py install



1. It is recommended not to run Easygui on IDLE

Easygui is run on Tkinter and has its own event loop, while IDLE is also an application written by Tkinter and has its own event loop. So when both are running at the same time, there is a risk of conflict and unpredictable results. So if you find that your Easygui program has this problem, try running your program outside of IDLE.


2. A simple example

In Easygui, all GUI interactions are through simple function calls, and a simple example below tells you that Easygui is really easy!

  1. Import Easygui as G
  2. Import Sys
  3. While 1:
  4. G.msgbox ("Hi, Welcome to the first interface mini-game ^_^")
  5. Msg= "What kind of knowledge do you want to learn from the fish C studio?" "
  6. title = "Small Game interaction"
  7. choices = ["Love", "Programming", "Ooxx", "Four Arts"]
  8. 10.
  9. Choice = G.choicebox (msg, title, choices)
  10. 12.
  11. #note that we convert choice to string
  12. #the user cancelled the choice, and we got None.
  13. G.msgbox ("Your choice is:" + str (choice), "result")
  14. 16.
  15. . msg = "Do you want to start the little game again?" "
  16. title = "Please select"
  17. 19.
  18. Ifg.ccbox (MSG, title): # Show a Continue/cancel dialog
  19. * Pass # User chose Continue
  20. . else:
  21. Sys.exit (0) # Userchose Cancel
  22. 24.

Copy Code



3. Easygui
's various function demos

To run the Easygui demo program, call Easygui at the command line:

    1. C:\Python33\python.exe easygui.py

Copy Code


Or you can call from the IDE (for example, IDLE, Pythonwin, Wing, and so on):

    1. >>> Import Easygui as G
    2. >>> G.egdemo ()

Copy Code


After a successful call you will be able to try the various features that Easygui has and print the results of your choice to the console.




4. import Easygui

In order to use the Easygui module, you should import it first. The simplest import statements are:

    1. Import Easygui

Copy Code


If you use the form above to import, then when you use the Easygui function, you must precede the function with a prefix Easygui, like this:

    1. Easygui.msgbox (...)

Copy Code


Another option is to import the entire Easygui package:

    1. From Easygui Import *

Copy Code


This makes it easier to invoke the Easygui function, which you can write directly:

    1. MsgBox (...)

Copy Code


The third scenario is to use an import statement similar to the following:

    1. Import Easygui as G

Copy Code


This allows you to maintain a Easygui namespace while reducing your typing volume. After importing, you can call the Easygui function as follows:

    1. G.msgbox (...)

Copy Code



5.
using Easygui

Once your module is imported the Easygui,gui operation is a simple matter of calling several parameters of the Easygui function.

For example, using Easygui to achieve the famous "Hello, world!" "The program is like this:

    1. Import Easygui as G
    2. G.msgbox ("Hello, world!")

Copy Code





6. Default parameters of the Easygui function

For all functions, the first two arguments are messages and headers. According to this rule, in some cases this may not be the most user-friendly arrangement (for example, dialogs ignore message parameters when retrieving directories and filenames), but I think it is a more important consideration to maintain this consistency throughout all widgets!

Most of the Easygui functions have default parameters, and almost all components display a message and a caption. The title defaults to an empty string, and the information usually has a simple default value.

This allows you to set the parameters as few as possible, such as the MsgBox () function in the title section of the parameter is optional, so you call MsgBox () When you can specify only a message parameter, for example:

    1. >>> MsgBox (' I love the Little Turtle ^_^ ')

Copy Code


Of course you can also specify the caption parameters and message parameters, for example:

    1. >>> MsgBox (' I love little Turtle ^_^ ', ' fish oil Voice ')

Copy Code




In the various button components, the default message is "shall icontinue", so you can call them without any parameters. Here we demonstrate to call Ccbox () without any parameters, and return a Boolean value when you select "Cancel" or close the window:

    1. If Ccbox ():
    2. Pass # User chose Tocontinue
    3. Else
    4. Return # user chose to cancel

Copy Code



7.
calling the Easygui function using the keyword argument

Calling the Easygui function also allows you to use the keyword parameter oh. (such as forgotten children's shoes to turn out "0 basic beginner Learning python" 18th, self-brain repair)

Now suppose you need to use a button component, but you don't want to specify the caption parameter (the second argument), you can still specify the choices parameter (the third parameter) using the method of the keyword argument, like this:

    1. >>> choices = [' Willing ', ' unwilling ', ' willing to have money ']
    2. >>> reply = Choicebox (' Would you like to purchase resources to pack support for the Little turtle? ', choices = choices)

Copy Code





8. using the button assembly

On demand, Easygui set up a series of functions for invocation on Buttonbox ().


8.1 MsgBox ()

MsgBox (msg= ' (Your message goes here) ', title= ', ok_button= ' OK ', Image=none, Root=none)

MsgBox () displays a message and provides an "OK" button, you can specify any message and caption, and you can even rewrite the contents of the "OK" button.
The following is an instance function of MsgBox ():

    1. Def MsgBox (msg= "(Your message Goeshere)", title= "", ok_button= "OK"):
    2. ....

Copy Code


The simplest way to rewrite the "OK" button is to use the keyword parameter:

    1. >>> MsgBox ("I must learn to program!", ok_button= "Come on!")

Copy Code





8.2 Ccbox ()

Ccbox (msg= ' shall I continue? ', title= ', choices= (' Continue ', ' Cancel '), Image=none)

Ccbox () provides a choice: Continue or Cancel, and returns 1 (checked Continue) or 0 (check cancel) accordingly.

Note that Ccbox () is a return integer of 1 or 0, not a Boolean type of True or False. But you can still write this:

    1. If Ccbox (' Do you want to do it again? ', choices= (' Want Ah ^_^ ', ' Forget it t_t ') '):
    2. MsgBox (' Do not play, play on the Bad ... ')
    3. Else
    4. Sys.exit (0) # Remember to import SYS first

Copy Code



8.3 Ynbox ()


Ynbox (msg= ' shall I continue? ', title= ', choices= (' Yes ', ' No '), Image=none)

Ditto, I do not know the author design These two things what ...


8.4 buttonbox ()

Buttonbox (msg= ", title=", choices= (' Button1 ', ' Button2 ', ' Button3 '), Image=none, Root=none)

You can use Buttonbox () to define your own set of buttons, and Buttonbox () displays a set of buttons that you have defined.

When the user clicks on any of the buttons, Buttonbox () returns the text content of the button. If the user cancels or closes the window, the default option (the first option) is returned. Take a look at the example:




8.5 indexbox ()

Indexbox (msg= ' shall I continue? ', title= ', choices= (' Yes ', ' No '), Image=none)

Basically the same as above, the difference is that when the user selects the first button to return the ordinal 0, select the second button when the return sequence number 1.


8.6 boolbox ()

Boolbox (msg= ' shall I continue? ', title= ', choices= (' Yes ', ' No '), Image=none)

Returns 1 if the first button is selected, otherwise 0.


9.how theButtonboxShow picture Inside

When you call a Buttonbox function (such as MsgBox (), Ynbox (), Indexbox (), and so on), you can also assign a value to the keyword parameter image, which is an image in a. gif format (note that only GIF format is supported):

    1. Buttonbox (' Everybody say I'm handsome? ', image= ' turtle.gif ', choices= (' handsome ', ' not Handsome ', ' [email protected]#$% ')]

Copy Code





provide users with a range of options

10.1 Choicebox ()

Choicebox (msg= ' Pick something. ', title= ', choices= ())

button components provide users with a simple button option, but a better strategy is to provide them with an optional list if there are many options, or if the content of the option is particularly long.

Choicebox () provides the user with an optional list that uses a sequence (a tuple or list) as an option, which is ordered in a case-insensitive manner before being displayed.

You can also use the keyboard to select one of the options (more tangled, but not important at all):


    • For example, when you press the "G" key on your keyboard, the first option that starts with "G" will be selected. Pressing the "G" Key again will select the next option that starts with "G". When you select the last option that starts with "G", pressing the "G" key again will return to the first option starting with "G" at the beginning of the list.
    • If the option does not start with "G", the option to start the character sort before "G" ("F") is checked
    • If no characters in the option are sorted before "G", then the first element in the list will be selected.


Combine the file features we learned before, and give up an example (source code in section *Speaking after-school homework^_^):




10.2 multchoicebox ()

Multchoicebox (msg= ' Pick as many items as Youlike. ', title= ', choices= (), **kwargs)

The Multchoicebox () function also provides an optional list, unlike Choicebox (), Multchoicebox () allows the user to select 0, 1, or multiple options at the same time.

The Multchoicebox () function is also used as an option for sequences (tuples or lists), which appear to be ordered in a case-insensitive manner before they are displayed.




One by one .Let the user enter a message

11.1 enterbox ()

Enterbox (msg= ' Enter something. ', title= ', default= ', Strip=true, Image=none, Root=none)

Enterbox () provides the user with one of the simplest input boxes, with the return value as a string entered by the user. The value returned by default automatically removes the leading and trailing spaces, and sets the parameter strip=false if you need to preserve the trailing spaces.




11.2 integerbox ()

Integerbox (msg= ", title=", default= ", Lowerbound=0, upperbound=99, Image=none, Root=none, * * invalidkeywordarguments)

Integerbox () provides the user with a simple input box, the user can only enter the range (lowerbound parameter set minimum value, upperbound parameter setting maximum value) of the integer value, otherwise it will require the user to re-enter.


11.3 multenterbox ()

Multenterbox (msg= ' Fill in values for Thefields. ', title= ', fields= (), values= ())

Multenterbox () to provide users with a number of simple input boxes, pay attention to the following points:


    • If the user enters a value that is less than the option, the value in the returned list fills the user with an empty string for the input option.
    • If the user enters more than one option, the value in the returned list is truncated to the number of options.
    • If the user cancels the operation, the value of the list in the domain or the None value is returned.


Implementation such as (source code in section *Speaking after-school homework^_^):




.Let the user enter the password

Sometimes we need to get the user to enter a password, which is what the user input looks like "*******".


12.1 passwordbox ()

passwordbox (msg= ' Enter your password. ', title= ', default= ', Image=none, Root=none)

PasswordBox () like the Enterbox () style, the difference is that the user-entered content is displayed with "*", returning the user-entered string:




12.2 Multpasswordbox ()

Multpasswordbox (msg= ' Fill in values for Thefields. ', title= ', fields= (), values= ())

Multpasswordbox () uses the same interface as Multenterbox (), but when it is displayed, the last input box appears in the form of a password ("*"):




.display text

Easygui also provides functions for displaying text.


13.1 textbox ()

textbox (msg= ", title=", text= ", codebox=0)

The Testbox () function defaults to displaying the text content in a proportional font (the parameter codebox=1 is set to the same width font), which is useful for displaying general written text.

Note: The text parameter (the third parameter) can be a string type, a list type, or a primitive type.




13.2 Codebox ()

Codebox (msg= ", title=", text= ")

Codebox () displays text content in equal-width font, equivalent to a TextBox (Codebox=1)

Note: equal width font is ugly, do not believe you try @[email protected]


.Directories and Files

A common scenario in GUI programming is to require users to enter directories and filenames, and Easygui provides some basic functions for users to browse the file system and select a directory or file.


14.1 Diropenbox ()

Diropenbox (Msg=none, Title=none,default=none)

The Diropenbox () function is used to provide a dialog box that returns the directory name selected by the user (with the full path) if the user chooses "Cancel" to return None.

The default parameter is used to set the defaults Open directory (make sure that the directory you set already exists).




14.2 Fileopenbox ()

Fileopenbox (Msg=none, title=none,default= ' * ', Filetypes=none)

The Fileopenbox () function is used to provide a dialog box that returns the file name selected by the user (with the full path) if the user chooses "Cancel" to return None.

about how to set the default parameter:


    • The default parameter specifies a path that typically contains one or more wildcard characters.
    • If the default parameter is set, Fileopenbox () displays the file path and format.
    • The default parameter is ' * ', which matches all formats of the file.


For example:


    1. default= "c:/fishc/*.py" displays all Python files under the C:\FISHC folder.
    2. default= "c:/fishc/test*.py" displays all Python files under the C:\FISHC folder whose names begin with Test.


About the Setup method for the FileTypes parameter:


    • Can be a list of strings that contain a file mask, for example: FileTypes =["*.txt"]
    • Can be a list of strings, the last string of the list is a description of the file type, for example: FileTypes =["*.css", ["*.htm", "*.html", "Htmlfiles"]



 


14.3 filesavebox ()

Filesavebox ( Msg=none, Title=none, default= ', Filetypes=none) the

Filesavebox () function provides a dialog box that allows you to select the path (with the full path) that the file needs to be saved. Returns None if the user selects "Cancel". The

default parameter should contain a file name (for example, the file name that you currently need to save), or you can set it to empty, or a wildcard character that contains a file format mask. The

FileTypes parameter is set up by referring to the top.

 


. remember users ' settings

15.1 egstore

A common scenario in GUI programming is to require the user to set parameters and save them so that the next time the user uses your program, they can remember his settings.

To implement the process of storing and recovering a user's settings, Easygui provides a class called Egstore. In order to remember certain settings, your application must define a class (temporarily called the "settings" class, although you arbitrarily set it with the name you want to inherit from the Egstore Class).

then your application must create an object of that class (temporarily called the "Settings" object). The

setting constructor for a class (the __init__ method) must initialize all of the values that you want it to remember.

Once you have done this, you can instantiate the variable in the Settings object by setting the value so that it is easy to remember the setting. Then use the Settings.store () method to persist the settings object on the hard disk.

The following is an example of creating a "settings" class:

    1. #-----------------------------------------------------------------------
    2. # create "Settings", apersistent Settings object
    3. # Note that the ' filename ' argument is required.
    4. # The directory for the persistent filemust already exist.
    5. #-----------------------------------------------------------------------
    6. Settingsfilename =os.path.join ("C:", "Fishcapp", "Settings.txt") # Windows Example
    7. Settings = settings (settingsfilename)

Copy Code


Here's an example of using the Settings object:

    1. # We initialize the "user" and "Server" variables
    2. # in a real application, we ' d probablyhave the user enter them via Enterbox
    3. user = "Obama"
    4. Server = "White House"
    5. # We save the variables as attributes ofthe "Settings" Object
    6. Settings.userid = user
    7. Settings.targetserver = Server
    8. Settings.store () # persistthe settings
    9. 10.

# Run code that gets a new value Foruserid

Persist the settings with the NewValue

user = "Little Turtle"

Settings.userid = user

Settings.store ()

Copy Code



Capturing exceptions

Exceptionbox ()

Using Easygui to write GUI programs can sometimes produce exceptions. Of course it depends on how you run your application, and when your application crashes, the stack trace may be thrown or written to the STDOUT standard output function.

Easygui provides a better way to handle exceptions by using the Exceptionbox () function, Exceptionbox () shows the stack trace in a codebox () and allows you to do further processing when an exception occurs.

Exceptionbox () is easy to use, here is an example:

    1. Try
    2. Print (' I love fishc.com! ')
    3. Int (' FISHC ') # This will produce an exception
    4. Except
    5. Exceptionbox ()

Copy Code



Easygui Learning Document "Super-detailed Chinese version"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.