Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use PyQT to make Video player in Python

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to use PyQT to make a video player in Python". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use PyQT to make a video player in Python.

Video player

Release the finished code 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.stateChanged.connect (self.handleStateChanged) self.video = Phonon.VideoWidget (self) self.video.setMinimumSize 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.info = 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-slot For time lapse self.thread = PollTimeThread (self) self.thread.update.connect (self.update) def update (self): # slot lapse = self.media.currentTime () / 1000.0 self.info.setText ("% 4.2f seconds"% lapse) def startPlay (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.PlayingState: self.media.stop () self.thread.terminate () Else: self.path = QtGui.QFileDialog.getOpenFileName (self Self.button.text () self.startPlay () def handleStateChanged (self, newstate Oldstate): if newstate = = Phonon.PlayingState: self.button.setText ('stop') elif (newstate! = Phonon.LoadingState and newstate! = Phonon.BufferingState): self.button.setText ('Select File') if newstate = = Phonon.ErrorState: source = self.media.currentSource () .fileName () print ('error: unable to play:' Source.toLocal8Bit () .data () print ('% s'% self.media.errorString () .toLocal8Bit () .data () if _ _ name__ ='_ _ main__': app = QtGui.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 video files. Video playback makes use of the Phonon module in PyQT. In addition, there is a process that sends a signal every other second. The window updates the time when the video is played after receiving the signal. The effect of this application is as follows:

The test run environment is Mac OSX El Capitan.

View section

After writing this code, I found that although the code is simple, it involves several important mechanisms, which can be used in PyQT exercises. The following is a brief description of the code, starting with the main program:

App = QtGui.QApplication (sys.argv)... window = Window () window.show () sys.exit (app.exec_ ())

In the PyQT program, QApplication is the top object, which refers to the whole GUI application. We create an application object at the beginning of the program and call exec_ () at the end of the program to run the application. Sys.exit () is used to require the application to exit cleanly at the end of the main loop. The beginning and end of a PyQT program are similar routines. The key lies in the QWidget objects defined between them.

Our custom Window class inherits from QWidget. In fact, QWidget is the base class of all user interface objects, not just referring to a window. Tables, input boxes, and buttons are all inherited from QWidget. In a Window object, we also combine objects such as QPushButton and QLabel, which represent a button and a text box, respectively. They are laid out on the interface of Window by QGridLayout, that 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) means to place a text box object in row 4, column 1. The text box will occupy 1 row vertically and 3 columns horizontally. In this way, the position relationship between the upper and lower views is determined by the layout. In addition to the grid layout, PyQT also supports other forms of layout, such as horizontal stacking, vertical stacking, and so on.

In addition to QWidget,PyQT, it also provides commonly used dialog boxes, such as:

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

The QFileDialog dialog box here is used to select a file. The dialog box accesses the path to the selected file. In addition to file selection, the dialog box has a confirmation dialog box, a file input dialog box, and a color dialog box. These dialogs implement many commonly used GUI input functions. By making use of these dialogs, you can reduce the workload of programmers' development from scratch.

Multithreading

The main thread of the GUI interface is usually left to the application as the main loop. A lot of other work has to be done through other threads. PyQT multithreaded programming is as simple as overriding the run () method of QThread:

Class PollTimeThread (QtCore.QThread): def _ init__ (self, parent): super (PollTimeThread, self). _ init__ (parent) def run (self):.

After you create a thread, you can simply call the start () method to run:

Self.thread = PollTimeThread ()... self.thread.start () # start thread... self.thread.terminate () # terminate thread signal and slot

Asynchronous processing is often used in GUI. For example, click a button and then call the corresponding callback function. The signal and slot (signal-slot) mechanism of QT is to solve the problem of asynchronous processing. We create a signal in the thread and signal it 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)

Whenever a signal is sent, the slot is called. In this example, the video playback time is updated. "signal and slot" in QT is a ubiquitous mechanism. Some components, such as buttons, preset signals such as "click", which can directly correspond to "slot". As in the code:

Self.button.clicked.connect (self.handleButton) so far, I believe you have a deeper understanding of "how to use PyQT to make a video player in Python". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report