The first time I wrote a complete Python GUI Program

Source: Internet
Author: User
Tags timedelta

Plug-ins are easy to be checked at night. Therefore, if you want to concentrate the food time on the day, You need to calculate the problem every time. You just learned wxpython. You can write it by yourself. Although purely entertaining, I have learned a lot. Note.

 

1. Python GUI Design

There has never been a good enough killer ide. No wonder that there is not a powerful background. It's easy to make it a heavyweight IDE (if Google pulls one, unfortunately Google has its own language go ).

 

Having tried countless designers (wxglade, wxformbuilder, farpy...), I finally thought BOA constructor was good, although its interface was not used (P.s. Do not maximize the running of BOA. Of course, manual double-clicking is okay, but it is hard to say with some quick management tools.

.In addition, F9 runs the entire project directly, which is quite convenient.

); Although it does not support Chinese characters well, it was updated in...

 

But this is already the best of these.

 

In response to the above deficiencies, I had to add "Hands" to help:

Using BOA to build a pure Gui has almost no business logic. In addition, in the files generated by BOA_ Init_ctrls

CodeNever touch it.
Otherwise, the frame designer cannot be loaded, which is the most valuable part of boa. But BOA does not have any code prompts (you can set it under explorer> preferences> key bindings). The editing function is much weaker than the following two, so you only use it for GUI. (P.s. must use the source code instead of binary, and can better support Unicode

)

 

The business logic Code uses pydev, which is a very good ide. Based on Eclipse, I also learned more about it. (For example, edit-> set encoding, right-click Refresh on SRC, and so on)

 

I used pyscripter to modify the Python code generated by BOA. There are three reasons: I didn't find how to add eclipse to it (too stupid. Later I found out that I am right-clicking refresh on SRC) modify the encoding format (now we know that we can use eclipse's set encoding), and provide better support for wxpython function prompts than eclipse (I have not found a good solution yet,P.s. manually add the module path.

). In addition, pyscripter also has a command line tool that is much better than idle. In addition, it is good to test some functions (P.s. pydev is fine. Just lock a console into the python console.

).

 

Combined with the wxpython demonstration, Python official documentation, and the omnipotent Google, the development was quite good.

 

2. About Python linguistics

① The GUI and business logic are almost completely separated (about 90%), from which we can see that this design is convenient for testing and the code generated by separation of business and GUI is clear.

② Static methods of the class:

@ Staticmethod <br/> def getcurrenttime (): Pass

③ Use datetime to conveniently add or subtract time:

Import datetime <br/> # Time after ahour hour aminute minutes <br/> dt = datetime. datetime (year = 2009, month = 11, Day = 11, hour = ahour, minute = aminute) <br/> Delta = datetime. timedelta (hours = bhour) <br/> DT + = delta <br/> Print DT. strftime ('% H: % m ')

In addition, a csdn Post says parse. When can I try it.

 

④ Using multiple timers in wxpython

Def initdata (Self): <br/> # all timers are bound to the same function <br/> self. BIND (wx. evt_timer, self. ontimer) <br/> # The last parameter ID is used to differentiate different timers <br/> self. TM1 = wx. timer (self, 1) <br/> self. tm1.start (1000) <br/> self. TM2 = wx. timer (self, 2) <br/> self. tm2.start (1000) <br/> def ontimer (self, EVT): <br/> id = EVT. GETID () <br/> If Id = 1: Pass <br/> Elif id = 2: Pass

(P.s. Later 《Wxpython in action
See another method in the last chapter:
)

Timer1 = wx. timer (Self) <br/> timer2 = wx. timer (Self) <br/> self. BIND (wx. evt_timer, self. ontimer1event, timer1) <br/> self. BIND (wx. evt_timer, self. ontimer2event, timer2)

⑤ Use multi-threaded programs

Later, I tried to use multiple threads to simulate multiple timers. Although this was not necessary, I learned something.

Def initdata (Self): <br/> self. timeat. setvalue ('10: 30') <br/> # Use thread to set timer to refresh current time <br/> threadgettime = threading. thread (target = self. timergettime) <br/> # setting the daemon attribute is very important. Therefore, if dameon is not set to true, <br/> # When the main process ends, the entire program can be completed only after each thread is finished <br/> # bundle, and the functions in the thread are infinite loops, therefore, the system will exit only when the operation on the window part <br/> # fails. Therefore, after the program ends, it will always wait for a while <br/> # And after the daemon is set to true, the main process immediately ends all threads. <br/> threadgettime. daemon = true <br/> threadgettime. start () <br/> # set timer to update crop time <br/> threadupdate = threading. thread (target = self. timerupdatecrop) <br/> threadupdate. daemon = true <br/> threadupdate. start () <br/> def timerupdatecrop (Self): <br/> while true: <br/> self. fillcrop () <br/> time. sleep (60) <br/> def timergettime (Self): <br/> while true: <br/> self. maturetime () <br/> time. sleep (1)

In addition, an IBM article suggested using processes rather than threads in Python:

Global interpreter lock indicates that the python interpreter is NOT thread-safe. The current thread must hold a global lock for secure access to Python objects. Because only one thread can obtain the python object/c api, the interpreter regularly releases and reacquires the lock every time it passes through 100 bytecode instructions. The interpreter can check the thread switching frequency throughsys.setcheckinterval()
Function.

In addition, the lock will be released and re-acquired based on potential blocking I/O operations. For more information, see references
In SectionGil and threading state
AndThreading the global interpreter lock
.

It should be noted that due to Gil, CPU-limited applications will not benefit from the use of threads. We recommend that you use processes or create processes and threads in a hybrid manner when using python.

In python2.6A great module such as multiprocessing removes the weakness of the thread, and multi-process becomes the strength.

TheMultiprocessing

Package offers both local and remote concurrency, please tively side-steppingGlobal interpreter lock

By using subprocesses instead of threads. Due to this,Multiprocessing

Module allows the programmer to fully leverage multiple processors on a given machine. It runs on both UNIX and windows.

(PS: in actual use, it is found that multiprocessing has many restrictions on the Windows platform, one of which is to require picklable
)

 

6. unit tests are used in Python:

Import farmtimer <br/> Import unittest <br/> class farmtimertestcase (unittest. testcase): <br/> def setup (Self): <br/> self. farmtimer = farmtimer () <br/> def teardown (Self): <br/> self. farmtimer = none <br/> def testgettimedelta (Self): <br/> self. assertequal (datetime. timedelta (minutes = 2), farmtimer. farm. gettimerdelta ("00:02") </P> <p> If _ name _ = '_ main _': <br/> unittest. main ()

 

7. SQLite was used, but later I found that such data is really not worth using the database, so I directly used tuple of tuple:

Crops = (
# Name, rank, Count, (times ,)
# Can be added Col before time
(U 'pasture ', 0, 1, (8 ,)),
(U 'White radish ', 0, 1, (10 ,)),

...)

 

Summary: learning programs depends on writing more. Writing a small program allows me to write so much, and there are still many topics worth further exploration. For example: after py2exe is packaged, it cannot run normally on XP, And the mutiprocess module is used. I will definitely be back!

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.