Build an application-based GUI with Python script

Source: Internet
Author: User
Tags call back
Create an application-based GUI using the Python script language to quickly start the developer online builder.com.cn. Updated on: 2007-02-27Author: builder.com.cn

When you want to learn a new language, especially a scripting language like python, before you fully begin to write the graphical interface of the application, sometimes you may be forced to use the application console.

Since the release of the first commercial graphic interface (if you are interested, you can view the Xerox star), after 25 years, it seems a little old to continue using the console on applications.

Thanks to the simplified syntax of the Python script language, this means that you can use the graphical user interface in your program without becoming a python programming expert. To prove this, I will use the python standard GUI (graphical user interface) tool TK to create a simple record session program. I will not describe Python's simple syntax in detail. If you have any questions, please read my previous articles on this topic (Click here and here to view them );

Let's start with the basics. First, you need to enter the TK interface to your program namespace. Because we will constantly reference the TK window widgets, we do not want to limit them with a package, so the best way is to do this:

From tkinter import *

The difference between this Import Statement and the traditional import statement is that it imports everything into the default namespace of the program in the module, instead of referencing a tkinter. you can only write text boxes when using textbox text boxes.

Now let's create a root window and set its title to explain something:

Root = TK ()

Root. Title ("note taker ")

Creating the root window is as simple as creating an instance of the TK class. It loads the graphics toolkit and provides us with a blank window that can load the widgets. This is the first part of the basic process for starting a TK program.

Root. mainloop ()

The second part (shown above) is to call the main loop of Tk. This main loop is used to handle events, such as Keyboard Events or mouse input, allow users to exchange information with the dialog box. In fact, at this time you really use the GUI program. Run a Python script in those four ways and a window will pop up, but this window is only placed there and it will not do any operation.

Place widgets in your window

Although this is very annoying, its interface includes the following widgets: buttons, forms, and so on, what these users can do. Now let's create some buttons, a text box, and a list box:

Button1 = button (root, text = "button1 ")

Button2 = button (root, text = "button2 ")

Button3 = button (root, text = "button3 ")

TEXT = entry (Root)

ListBox = ListBox (Root)

It is very easy to create basic objects. When each class is initialized, the first parameter belongs to the Window widget surface. In this case, we can only get the root window. The text attribute of the button can be used to set the tag of the button. There are many types of widgets, and there are also many ways to customize these widgets, but in this program we need a lot of such widgets-a complete list, click here if you want to view the official tkinter documentation. Now, we need to delete these widgets using the following package method:

Text. Pack ()

Button1.pack ()

Button2.pack ()

Button3.pack ()

ListBox. Pack ()

In a window, the order in which the widgets are packed is the order they are displayed on the screen. After running this program, the window you see is similar to the one shown in the following figure. It depends on the features of your operating system or window manager.

Interaction between widgets

Now it looks more interesting, but it has never really done anything. You can click a button or enter some information in the text box, but there are not many points to it. Now let's change this. Using TK and the GUI toolkit in it is called by calling the call back signal when an event occurs. Let's write a simple call back signal to provide feedback when you press button 1:

Def button1 ():

ListBox. insert (end, "button1 pressed ")

This function adds the "press button 1" string to end these items in the list box. When the button is pressed, we need to call this function to change the creation of Button 1 in the following way:

Button1 = button (root, text = "button1", command = button1)

Create a new call back function for button 2 in the same way. This function is used to insert different strings to the list box when the second button is pressed, and then debug the program. It is quite certain that pressing the button will change the content of the list box. If we are bored with these strings, what new things do we want to add in the dialog box?

Def button3 ():

Text_contents = text. Get ()

ListBox. insert (end, text_contents)

Text. Delete (0, end)

Then set the button 3 command to achieve this function. When you click this button, button 3 calls back the signal to first obtain the content of the text box, insert it to the bottom of the list box, and then clear the text box. Load the program and debug it.

If you execute this button, it may look like it stops working after a while. In fact, the list box is full. In fact, it works well, but we can only see the group of options at the top of the list, but we can scroll through the mouse wheel to see the remaining list. This is a bit bulky. Here we need a scroll bar so that we can select what we want to see in the list. If we use the following statement to create a list box, adding a scroll bar is a little more complicated than adding any part in other widgets, because we must associate it with the list box:

Scrollbar = scrollbar (root, orient = vertical)

ListBox = ListBox (root, yscrollcommand = scrollbar. Set)

Scrollbar. Configure (command = ListBox. yview)

Then, when we move the scroll bar around it, the position (vertical) of the Y axis of the list box will be changed ). In addition, if we use the scroll wheel to scroll the list box, the position of the scroll bar will be updated.

If you keep following, the Code should look like the following:

#! /Usr/bin/Python

From tkinter import *

Root = TK ()

Root. Title ("note taker ")

Def button1 ():

ListBox. insert (end, "button1 pressed ")

Def button2 ():

ListBox. insert (end, "button2 pressed ")

Def button3 ():

Text_contents = text. Get ()

ListBox. insert (end, text_contents)

Text. Delete (0, end)

Button1 = button (root, text = "button1", command = button1)

Button2 = button (root, text = "button2", command = button2)

Button3 = button (root, text = "button3", command = button3)

TEXT = entry (Root)

Scrollbar = scrollbar (root, orient = vertical)

ListBox = ListBox (root, yscrollcommand = scrollbar. Set)

Scrollbar. Configure (command = ListBox. yview)

Text. Pack ()

Button1.pack ()

Button2.pack ()

Button3.pack ()

ListBox. Pack ()

Scrollbar. Pack ()

Root. mainloop ()

Placement window Widgets

We start to deploy these places. We can enter our text information into the text box and add them to a list. Although this program is not very nice, everything is vertically discharged, the text box and the list box are too small to use. We need more control over the location where the widget is placed.

There are some ways to do this, but we will actually divide the window into two parts, one is the text box and button, and the other is the control list box. We will use the frame widget to implement this function. The frame widget looks like a container and can place other widgets inside it just like a root window. Now let's create a pair of frameworks

Textframe = frame (Root)

Listframe = frame (Root)

So far, we have set the owner of each widget as the root window. Next, we change its owner and apply it to our new design:

Button1 = button (textframe, text = "button1", command = button1)

Button2 = button (textframe, text = "button2", command = button2)

Button3 = button (textframe, text = "button3", command = button3)

TEXT = entry (textframe)

Scrollbar = scrollbar (listframe, orient = vertical)

ListBox = ListBox (listframe, yscrollcommand = scrollbar. Set)

Scrollbar. Configure (command = ListBox. yview)

In fact, this will not play much role unless we tell the TK widget to place the position in the frame. To achieve this, we can use the package method and three key words: side, fill, and expand. In a text processor, you can think of edges as similar to alignment. It tells the Window widget frame which side they generally need to set, which is the top and bottom, on the left and right -- the default form is group-centered. In this case, apart from being used as the scroll bar of the Left alignator, We Need To enclose everything else with the scroll bar to the right of the list box.

The second option is fill. If it increases, it will tell TK which direction overflows the small window part, in the X axis direction (horizontal direction), Y axis direction (vertical direction) or both directions are available. In general, we can handle these buttons well, however, it requires as much space as possible for the text box and the list box -- so it sets the text box to overflow on the X axis and the list box to overflow in both directions -- the scroll bar should reset the size of the list box, therefore, it is set to overflow in the Y axis.

Finally, the expand option tells the widget if it is possible to expand to free space-Add the expand = 1 Statement to the text box and the list box package option to achieve this effect. Now, your code should look like the following:

Text. Pack (side = left, fill = x, expand = 1)

Button1.pack (side = left)

Button2.pack (side = left)

Button3.pack (side = left)

ListBox. Pack (side = left, fill = both, expand = 1)

Scrollbar. Pack (side = right, fill = y)

Currently, all buttons on the left are packed into two frames and placed in the root window like other widgets. Remember, the framework should be expanded in this way:

Textframe. Pack (fill = X)

Listframe. Pack (fill = both, expand = 1)

Finally, we should set the default window size so that the window of our Window widget can have more space.

Root. Geometry ("600x400 ")

After these steps, our window should now look like the following:

Keyboard and mouse events

We have some work, more or less -- but its interface has always been a little impractical. If we can use the mouse and keyboard to make things more direct, the work will be easier to handle. When you run the TK main loop and press a key on the keyboard or move the mouse around to generate an event, you can bind the call back function to the button in the same way, in this way, when the button is pressed, the corresponding event is generated. Now we have a function to handle this situation, that is, the call back signal of button 3, but unfortunately, we cannot use it now, because the call-back signal of the button event is different from that of the mouse and keyboard. We must limit it to other functions:

Def returninsert (event ):

Button3 ()

Then we register the call back signals for these events and look for the binding function:

Text. BIND ("<return>", returninsert)

Here we use the <return> Event code instead of the <enter> Event code, which is very important because the second trigger is triggered when the mouse enters the list box. Now we want users to right-click to move projects from the list box, which is quite good for the same processing. First, write a call back signal as the input to receive events:

Def deletecurrent (event ):

ListBox. Delete (Anchor)

Then we bind the event to this call signal:

ListBox. BIND ("<double-button-3>", deletecurrent)

Right-click the button-3 in TK (do not confuse it with the name of our third form button call back signal), because the second mouse button involves the middle mouse key. Finally, just in case they want to modify it, we can allow users to copy an easy post and return it to the text box. No function can implement this function, so we have to write some new code in the call back signal:

Def copytotext (event ):

Text. Delete (0, end)

Current_note = ListBox. Get (Anchor)

Text. insert (0, current_note)

Then bind the event to the call back signal as previously:

ListBox. BIND ("<double-button-1>", copytotext)

You can not only restrict these events. If you want to know more about which events you can bind, please refer to the introduction of the TK internal library.

It seems that it is time to sort out our programs. Button 1 is a bad name for a function. Similar names once put us in trouble. Here we should not repeat the same mistakes. We also have the opportunity to change some button functions. For example, we can set the input button to close the text box. Button 1 has no special effect, so we can remove it. Modifying these changes does not really change the functionality, but the program now looks like this:

#! /Usr/bin/Python

From tkinter import *

Root = TK ()

Root. Geometry ("600x400 ")

Root. Title ("note taker ")

Def enter ():

Text_contents = text. Get ()

ListBox. insert (end, text_contents)

Text. Delete (0, end)

Def remove ():

ListBox. Delete (Anchor)

Def save ():

Pass

Def returninsert (event ):

Enter ()

Def deletecurrent (event ):

Remove ()

Def copytotext (event ):

Text. Delete (0, end)

Current_note = ListBox. Get (Anchor)

Text. insert (0, current_note)

Textframe = frame (Root)

Listframe = frame (Root)

Enter_button = button (textframe, text = "enter", command = enter)

Remove_button = button (textframe, text = "Remove", command = remove)

Save_button = button (textframe, text = "save", command = save)

TEXT = entry (textframe)

Scrollbar = scrollbar (listframe, orient = vertical)

ListBox = ListBox (listframe, yscrollcommand = scrollbar. Set, selectmode = extended)

Scrollbar. Configure (command = ListBox. yview)

Text. BIND ("<return>", returninsert)

ListBox. BIND ("<double-button-3>", deletecurrent)

ListBox. BIND ("<double-button-1>", copytotext)

Text. Pack (side = left, fill = x, expand = 1)

Enter_button.pack (side = left)

Remove_button.pack (side = left)

Save_button.pack (side = left)

ListBox. Pack (side = left, fill = both, expand = 1)

Scrollbar. Pack (side = right, fill = y)

Textframe. Pack (fill = X)

Listframe. Pack (fill = both, expand = 1)

Root. mainloop ()

Save data between sessions

After this is done, our program can be used, but when we close the program, the easy-to-use stickers will disappear-we can save the list content to a file, at the same time, download it to install the program while the program is running. To achieve this, we will use the pickle module-Python series, or use the data types to be released to the file. First, we need to enter the module:

Import pickle

Then we get a variable, Yishi, which contains the list of Yishi. To save it to a file, we only need to open the file and write it, and use the dump function. You may notice that the call-back signal of the third button is empty. Let's change it to save the current event list to the file:

Def save ():

F = file ("notes. DB", "WB ")

Notes = ListBox. Get (0, end)

Pickle. Dump (notes, F)

Now, when you press the "save" button, we can get a copy of our notebook on the desktop. This will not give us much help, unless we have some methods to download these stickers, so let us correctly fill the list box before starting the main loop:

Try:

F = file ("notes. DB", "rb ")

Notes = pickle. Load (f)

For item in notes:

ListBox. insert (end, item)

F. Close ()

Except t:

Pass

We need to use a try statement to bundle everything to prevent an exception from opening the file. That is to say, if the file "notes. DB" does not exist, an exception should be thrown to generate a warning. However, if an exception is thrown, we will not really notice it, but we will not download any easy post to the list.

In this way, you have a mini easy-to-install program written in Python and TK, which contains up to 70 lines of code. It can be run with keyboard and mouse input, you can also download and save data. With this, you can see how simple it is to create a fast GUI based on an application, but this program has only a few improvements, such as the multi-threaded text area, or copy an easy sticker to the clipboard to automatically save it, and so on. It is an appropriate way to save your trace to the list. I will leave this as an exercise. If you want to find more text blocks about what you can do with python in TK, the best thing is to view the library files here. If you keep following the steps, the program should look like the following:

The code for this example is as follows:

#! /Usr/bin/Python

From tkinter import *

Import pickle

Root = TK ()

Root. Geometry ("600x400 ")

Root. Title ("note taker ")

Def enter ():

Text_contents = text. Get ()

ListBox. insert (end, text_contents)

Text. Delete (0, end)

Def remove ():

ListBox. Delete (Anchor)

Def save ():

F = file ("notes. DB", "WB ")

Notes = ListBox. Get (0, end)

Pickle. Dump (notes, F)

Def returninsert (event ):

Enter ()

Def deletecurrent (event ):

Remove ()

Def copytotext (event ):

Text. Delete (0, end)

Current_note = ListBox. Get (Anchor)

Text. insert (0, current_note)

Textframe = frame (Root)

Listframe = frame (Root)

Enter_button = button (textframe, text = "enter", command = enter)

Remove_button = button (textframe, text = "Remove", command = remove)

Save_button = button (textframe, text = "save", command = save)

TEXT = entry (textframe)

Scrollbar = scrollbar (listframe, orient = vertical)

ListBox = ListBox (listframe, yscrollcommand = scrollbar. Set, selectmode = extended)

Scrollbar. Configure (command = ListBox. yview)

Text. BIND ("<return>", returninsert)

ListBox. BIND ("<double-button-3>", deletecurrent)

ListBox. BIND ("<double-button-1>", copytotext)

Text. Pack (side = left, fill = x, expand = 1)

Enter_button.pack (side = left)

Remove_button.pack (side = left)

Save_button.pack (side = left)

ListBox. Pack (side = left, fill = both, expand = 1)

Scrollbar. Pack (side = right, fill = y)

Textframe. Pack (fill = X)

Listframe. Pack (fill = both, expand = 1)

Try:

F = file ("notes. DB", "rb ")

Notes = pickle. Load (f)

For item in notes:

ListBox. insert (end, item)

F. Close ()

Except t:

Pass

Root. mainloop ()

 

Related Article

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.