Python pyqt5 button click

Buttons and Events

This PyQt5 Tutorial will show you how to create buttons and trigger events using pyqt.

Creating Buttons

Our goal in this tutorial will be to create a button that will change the text of the label in the window.

To create a button we will follow a similar procedure as to when we created the label. Place the following into the function we created previously.

 b1 = QtWidgets.QPushButton(win) b1.setText("click me") #b1.move(100,100) to move the button 

pyqt-button.png

And now we have a button!

Events & Signals

The next thing to do is link our button to some kind of event so that something happens when it is clicked. This brings us to a new topic called Event-Driven-Programming. I won't explain this in detail as it's pretty intuitive but essentially the way that PyQt and many other GUI frameworks work is by waiting for events or signals (terms interchangeable) to occur. An example of an event/signal is a mouse hover over a button. When these events occur they trigger something to run (usually a function or method) that will handle what should happen.

For our case we need to handle a press on the button. So, we will start by creating a function that can be called when the event is triggered.

def clicked(): print("clicked") # we will just print clicked when the button is pressed 

Next we will link the button click event to that function. This is done with the following line:

 b1.clicked.connect(clicked) # inside main function # Note: you don't need the brackets for the function argument (thing in brackets) 

And now "clicked" will be printed each time we click the button.

OOP Implementation

Up until this point we have created a very basic GUI application inside of a function. This is fine for a small program, but will not scale very well as our GUI becomes more advanced. To fix this we are going to change our current code and write it using OOP (I have some python OOP tutorial here)!

Our code is translated into the following. Notice the use of inheritance. Since we are inherting from QMainWindow wherever we previously mentioned win we will replace with self.

from PyQt5 import QtWidgets from PyQt5.QtWidgets import QApplication, QMainWindow import sys class MyWindow(QMainWindow): def __init__(self): super(MyWindow,self).__init__() self.initUI() def button_clicked(self): print("clicked") def initUI(self): self.setGeometry(200, 200, 300, 300) self.setWindowTitle("Tech With Tim") self.label = QtWidgets.QLabel(self) self.label.setText("my first label!") self.label.move(50,50) self.b1 = QtWidgets.QPushButton(self) self.b1.setText("click me!") self.b1.clicked.connect(self.button_clicked) def window(): app = QApplication(sys.argv) win = MyWindow() win.show() sys.exit(app.exec_()) window() 

Changing Label Text

Now that we've changed to an OOP approach we can use the method button_clicked() to modify the label when the button is pressed.

 def button_clicked(self): print("clicked") self.label.setText("you pressed the button") 

label-pyqt.png

But wait. When we click the button to change the label it cuts off the last few characters. Luckily we can fix this by updating the labels size property after changing it.

Let's add an update method and call it from the button_clicked() method.

class MyWindow(QMainWindow): ... def clicked_button(self): self.label.setText("you pressed the button") self.update() ... def update(self): self.label.adjustSize() 

And now our label resizes properly

Full Code

from PyQt5 import QtWidgets from PyQt5.QtWidgets import QApplication, QMainWindow import sys class MyWindow(QMainWindow): def __init__(self): super(MyWindow,self).__init__() self.initUI() def button_clicked(self): self.label.setText("you pressed the button") self.update() def initUI(self): self.setGeometry(200, 200, 300, 300) self.setWindowTitle("Tech With Tim") self.label = QtWidgets.QLabel(self) self.label.setText("my first label!") self.label.move(50,50) self.b1 = QtWidgets.QPushButton(self) self.b1.setText("click me!") self.b1.clicked.connect(self.button_clicked) def update(self): self.label.adjustSize() def window(): app = QApplication(sys.argv) win = MyWindow() win.show() sys.exit(app.exec_()) window() 

Источник

pyqt5 button

PyQt5 supports buttons using the QPushButton class. This class is inside the PyQt5.QtWidgets group. The button can be created by calling the constructor QPushButton with the text to display as parameter.

Related course:

Introduction
To use buttons with a PyQt5 application, we need to update our import line:

from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtCore import pyqtSlot

In the initUI() method, add these lines of code:

button = QPushButton('PyQt5 button', self)
button.setToolTip('This is an example button')
button.move(100,70)

QPushButton creates the widget, the first argument is text on the button.
The method setToolTip shows the message when the user points the mouse on the button.
Finally the button is moved to the coordinates x=100,y=70.
We need to create a method for a button click:

@pyqtSlot()
def on_click(self):
print('PyQt5 button click')

Add connect the method to the click with:

button.clicked.connect(self.on_click)

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App(QWidget):

def __init__(self):
super().__init__()
self.title = 'PyQt5 button - pythonspot.com'
self.left = 10
self.top = 10
self.width = 320
self.height = 200
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

button = QPushButton('PyQt5 button', self)
button.setToolTip('This is an example button')
button.move(100,70)
button.clicked.connect(self.on_click)

self.show()

@pyqtSlot()
def on_click(self):
print('PyQt5 button click')

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

If you are new to programming Python PyQt, I highly recommend this book.

pyqt5-button

Screenshot of PyQt5 button example above.

Источник

PyQt5 - Button example, Python GUI

A button or command button is probably the most common widget in any graphical user interface.

Click the button to command the computer to perform an action or answer a question. Typical buttons are OK, apply, cancel, close, yes, no and help.

A button is rectangular and usually displays a text label that describes its actions. Shortcuts can be specified for buttons.

QPushButton

The button widget is called QPushButton. The QPushButton widget provides a default button.

from PyQt5.QtWidgets import QPushButton
pybutton = QPushButton('Click me', self)
pybutton.resize(100,32)
pybutton.move(50, 50)
pybutton.clicked.connect(self.clickMethod)

The first line creates an object of the type QPushButton.

The first argument is the text shown on the button:

pybutton = QPushButton('Click me', self)

The appearance depends on the operating system and the configured theme, something like this:

QPushButton pyqt button

We resize it to 100 pixels in width and 32 in height.

Then we set it to position (50,50) on the window.

The click must be linked to a Python method, clickMethod().

pybutton.clicked.connect(self.clickMethod)

pyqt5 button example

The program below creates a desktop window with a button inside of it.
By clicking the button it will call the method clickMethod().

The appearance of the window depends on the operating system.

import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtCore import QSize

class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)

self.setMinimumSize(QSize(300, 200))
self.setWindowTitle("PyQt button example - pythonprogramminglanguage.com")

pybutton = QPushButton('Click me', self)
pybutton.clicked.connect(self.clickMethod)
pybutton.resize(100,32)
pybutton.move(50, 50)

def clickMethod(self):
print('Clicked Pyqt button.')

if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
sys.exit( app.exec_() )

pyqt button example, QPushButton

PyQt Button example

The button can display a text label and can also select a small icon.

These can be set using constructor settings, which can be changed later using setText() and setIcon() .

If the button is disabled, the appearance of the text and icons is related to the GUI style to make the button look “disabled.”

self.button3.setEnabled(False)

When a button is activated by a mouse, space bar, or keyboard shortcut, the button sends a clicked() signal.

Connect to this signal to perform the action of the button. Buttons also provide less-used signals, such as pressed() and released() .

self.button3.clicked.connect(self.Action)

The program below shows various buttons in the window. It adds different types of buttons:

  • Button 1 is a default button, a QPushButton
  • Button 2 has a dropdown, by clicking it shows a menu QMenu
  • Button 3 gets disabled for a few seconds and renabled using a QTimer

python pyqt5 buttons

import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget, QMenu
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtCore import QSize, QTimer

class Example(QMainWindow):

def __init__(self):
QMainWindow.__init__(self)

self.setMinimumSize(QSize(320, 200))
self.setWindowTitle("PyQt button example - pythonprogramminglanguage.com")

self.bt1 = QPushButton("Button 1",self)
self.bt2 = QPushButton("Button 2",self)
self.bt3 = QPushButton('Button 3',self)

self.bt1.move(50,50)
self.bt2.move(50,100)
self.bt3.move(170,100)

menu = QMenu(self)
menu.addAction('Fruit')
menu.addSeparator()
menu.addAction('Cookies')
menu.addSeparator()
menu.addAction('Ice cream')
self.bt2.setMenu(menu)

self.bt1.clicked.connect(self.Button1)
self.count = 10
self.bt3.clicked.connect(self.Action)
self.time = QTimer(self)
self.time.setInterval(1000)
self.time.timeout.connect(self.Refresh)
self.show()

def Button1(self):
print('Clicked')

def Action(self):
if self.bt3.isEnabled():
self.time.start()
self.bt3.setEnabled(False)

def Refresh(self):
if self.count > 0:
self.bt3.setText(str(self.count)+' seconds')
self.count -= 1
else:
self.time.stop()
self.bt3.setEnabled(True)
self.bt3.setText('Button 3')
self.count = 10

if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = Example()
mainWin.show()
sys.exit( app.exec_() )

In this example above, we implement three functions: menu buttons, buttons with countdowns (which are often encountered when accounts are registered) and a default click function.

The button menu QMenu is added to the button like this:

menu = QMenu(self)
menu.addAction('Fruit')
menu.addSeparator()
menu.addAction('Cookies')
menu.addSeparator()
menu.addAction('Ice cream')
self.bt2.setMenu(menu)

For the other example, we used the QTimer class, this is a time-related class.

The QTimer class provides repeatability and single timers. The QTimer class provides an advanced programming interface for timers.

To use it, create a QTimer, connect its timeout() signal to the appropriate slot, and then call start().

self.time = QTimer(self)
self.time.setInterval(1000)
self.time.timeout.connect(self.Refresh)

From then on, it will send out signals at regular intervals. SetInterval() This property has a time-out interval in milliseconds. The default value for this property is 0.

Источник

Читайте также:  Import function from module python
Оцените статью