Python app 03 making video player using PYQT

Source: Internet
Author: User
Tags emit

Vamei source: Http://www.cnblogs.com/vamei prohibited any form of reprint.

A recent study of Python's two GUI packages, tkinter and Pyqt. The bottom layer of the two GUI packages is TCL/TK and Qt respectively. By contrast, I think PYQT is more convenient to use and more versatile. This article uses PYQT to implement a video player, and to illustrate the basic usage of pyqt.

Video player

Let's put the finished code out First. The code is based on Python 3.5:

Import timeimport sysfrom PyQt4 import qtgui, qtcorefrom pyqt4.phonon import phononclass polltimethread (qtcore.qthread):    "" This thread works as a timer.    "" "update = qtcore.pyqtsignal () def __init__ (self, parent): Super (polltimethread, self). __init__ (parent)                def run (self): while True:time.sleep (1) if self.isrunning (): # emit signal        Self.update.emit () else:returnclass Window (qtgui.qwidget): def __init__ (self): qtgui.qwidget.__init__ (self) # Media self.media = Phonon.mediaobject (self) self.media.stateCha Nged.connect (self.handlestatechanged) self.video = phonon.videowidget (self) self.video.setMinimumSize (200, 2        Xx) Self.audio = phonon.audiooutput (phonon.videocategory, self) phonon.createpath (self.media, self.audio) Phonon.createpath (self.media, self.video) # control button Self.button = QTGUI.QPUSHBUtton (' Select File ', self) self.button.clicked.connect (self.handlebutton) # for display of time lapse self.i  NFO = Qtgui.qlabel (self) # layout layout = qtgui.qgridlayout (self) layout.addwidget (self.video, 1, 1, 3, 3) layout.addwidget (self.info, 4, 1, 1, 3) layout.addwidget (self.button, 5, 1, 1, 3) # Signal-slo t, for-time Lapse self.thread = Polltimethread (self) self.thread.update.connect (self.update) def update (s Elf): # slot lapse = self.media.currentTime ()/1000.0 self.info.setText ("%4.2f sec"% Lapse) def star  Tplay (self): if Self.path:self.media.setCurrentSource (phonon.mediasource (self.path)) # Use a            Thread as a timer Self.thread = Polltimethread (self) self.thread.update.connect (self.update) Self.thread.start () self.media.play () def handlebutton (self): if self.media.state () = = phonon.pl Ayingstate:sElf.media.stop () self.thread.terminate () else:self.path = QtGui.QFileDialog.getOpenFileName ( self, Self.button.text ()) self.startplay () def handlestatechanged (self, newstate, oldstate): if Newst              ate = = Phonon.PlayingState:self.button.setText (' stop ') elif (newstate! = phonon.loadingstate and newstate! = phonon.bufferingstate): self.button.setText (' Select File ') if newstate = = Phonon.errorstat E:source = Self.media.currentSource (). fileName () print (' error: cannot play: ', source.tolocal8bit (). da Ta ()) print ('%s '% self.media.errorString (). tolocal8bit (). data ()) if __name__ = = ' __main__ ': app = Qtg Ui. Qapplication (sys.argv) app.setapplicationname (' video playback ') window = window () window.show () sys.exit (app.exec_ ())

The code implements an application with a GUI window to play the video File. Video playback utilizes the phonon module in the Pyqt. In addition, there is a process that sends a signal every SECOND. The window updates the video playback time after the signal is Received. The effect of this application is as Follows:

Test run Environment for Mac OSX El Capitan.

View section

After writing this code, I found that this code is simple, but involves a few important mechanisms, you can use PYQT Exercises. The following is a brief description of the code, first of all the main program section:

App = qtgui.qapplication (sys.argv) ... window = window () window.show () sys.exit (app.exec_ ())

In the PYQT program, qapplication is the topmost object that refers to the entire GUI Application. We created an Application object at the beginning of the program and then called Exec_ () at the end of the program to run the Application. Sys.exit () is used to require the Application's main loop to exit cleanly after the end of the Program. The beginning and end of the PYQT program are similar fixed routines. The key is the Qwidget object that is defined in the Meantime.

Our custom window class inherits from Qwidget. In fact, Qwidget is the base class for all user interface objects and does not refer to just one window. tables, input boxes, and buttons are inherited from Qwidget. In a window object, we also combine objects such as Qpushbutton and qlabel, representing a button and a text box, respectively. They are arranged in a qgridlayout way, in the interface of the window, which is the following part of the Code:

# layoutlayout = Qtgui.qgridlayout (self) ... layout.addwidget (self.info, 4, 1, 1, 3) layout.addwidget (self.button, 5, 1, 1, 3)

Qgridlayout divides the interface into meshes and attaches a view object to a specific grid Location. For example, addwidget () (self.info, 4, 1, 1, 3) indicates that a text box object is placed in the position of the 4th row and 1th Column. The text box will occupy 1 rows vertically and occupy 3 columns Horizontally. In this way, the position relationship of the upper and lower views is determined by the Layout. In addition to the layout of the net format, PYQT also supports other forms of layout, such as horizontal stacking, vertical stacking, etc., can be further understood.

In addition to qwidget,pyqt, a common dialog box is provided, such as:

Self.path = QtGui.QFileDialog.getOpenFileName (self, self.button.text ())

The Qfiledialog dialog box here is used to select the File. The dialog box accesses the path to the selected File. In addition to file selection, the dialog box also has a confirmation dialog, a file input dialog, and a color dialog box. These dialogs implement a number of common GUI input functions. By using these dialogs, you can reduce the amount of work the programmer is developing from Scratch.

Multithreading

The main thread of the GUI interface is usually left to the application master Loop. Much of the other work is done through other THREADS. PYQT multithreaded programming is simple, only need to rewrite the qthread run () method, you can:

Class Polltimethread (qtcore.qthread):    def __init__ (self, parent):        Super (polltimethread, self). __init__ ( Parent)    def run (self):        ...

Once the thread is created, it is only necessary to call the start () method to Run:

Self.thread = Polltimethread ()
... self.thread.start () # Start thread
... self.thread.terminate () # terminating thread

Signal and slot

The GUI often uses asynchronous processing. For example, click on a button and invoke the corresponding callback Function. Qt's "signal and groove" (signal-slot) mechanism is designed to solve asynchronous processing Problems. We created the signal in the thread and signaled through the emit () method:

Class Polltimethread (qtcore.qthread): "" "this    thread works as a timer.    " " Update = qtcore.pyqtsignal ()    def __init__ (self, parent):        Super (polltimethread, self). __init__ (parent)    def run (self): while        True:            time.sleep (1)            if self.isrunning ():                # Emit signal                Self.update.emit ( )            Else:                return

With the signal, we can connect the signal to a "slot", which is actually the callback function corresponding to the Signal:

Self.thread.update.connect (self.update)

Each time the signal is emitted, the "slot" is Called. In this example, the video playback time is Updated. The "signal and groove" in Qt is a universal mechanism. Some of the settings, such as buttons, preset "click" such a signal, can directly correspond to the "slot." As in the Code:

Self.button.clicked.connect (self.handlebutton)

In addition, phonon is a very useful multimedia module, the use of the method is very simple, you can refer to the code itself, here no longer repeat.

Welcome to the Python quick tutorial

Python app 03 using PYQT to create a video player

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.