How to make a small Button in Python without Tkinter - python

in Python without using tkinter, can anyone help?
Here's the code i'd like to add it to:
import time
pswrd = '12345678'
while True:
m = input("1.Login 2.Reset Password\n")
if m == "1":
n = input("Password:\n")
if n == pswrd:
print("Password Correct\n")
else:
print("Wrong Password\n")
else:
n = input("New Password:\n")
pswrd = n
repeat = 'While True'
Im starting to make some tests for an Os i want to build, i know, it's big of a goal but yeah... It just helps me train my newbie skills x)
Can anyone help with it plsss ?

Use python Kivy or python pyQT.
Example:
Button with Kivy:
# import kivy module
import kivy
# this restrict the kivy version i.e
# below this kivy version you cannot
# use the app or software
kivy.require("1.9.1")
# base Class of your App inherits from the App class.
# app:always refers to the instance of your application
from kivy.app import App
# creates the button in kivy
# if not imported shows the error
from kivy.uix.button import Button
# class in which we are creating the button
class ButtonApp(App):
def build(self):
# use a (r, g, b, a) tuple
btn = Button(text ="Push Me !",
font_size ="20sp",
background_color =(1, 1, 1, 1),
color =(1, 1, 1, 1),
size =(32, 32),
size_hint =(.2, .2),
pos =(300, 250))
# bind() use to bind the button to function callback
btn.bind(on_press = self.callback)
return btn
# callback function tells when button pressed
def callback(self, event):
print("button pressed")
print('Yoooo !!!!!!!!!!!')
# creating the object root for ButtonApp() class
root = ButtonApp()
# run function runs the whole program
# i.e run() method which calls the target
# function passed to the constructor.
root.run()
Button with pQT:
# importing libraries
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
class Window(QMainWindow):
def __init__(self):
super().__init__()
# setting title
self.setWindowTitle("Python ")
# setting geometry
self.setGeometry(100, 100, 600, 400)
# calling method
self.UiComponents()
# showing all the widgets
self.show()
# method for widgets
def UiComponents(self):
# creating a push button
button = QPushButton("CLICK", self)
# setting geometry of button
button.setGeometry(200, 150, 100, 30)
# adding action to a button
button.clicked.connect(self.clickme)
# action method
def clickme(self):
# printing pressed
print("pressed")
# create pyqt5 app
App = QApplication(sys.argv)
# create the instance of our Window
window = Window()
# start the app
sys.exit(App.exec())

Related

PyQt5 application: button press event not working [duplicate]

Hopefully I am following the guidelines correctly here with my first question. I am trying to create a GUI with the MVC structure. I am having difficulty with understanding why my signals are not always being picked up by the controller. I know that there is just something simple that I'm missing. I'm attaching code from a simple calculator which I used as a guide. I removed most of the features to simplify this as much as possible. It is now only 3 of the original buttons and my own button. For debugging, I just have the value on the button printed out when you press it.
import sys
# Import QApplication and the required widgets from PyQt5.QtWidgets
from PySide2.QtWidgets import QApplication
from PySide2.QtWidgets import QMainWindow
from PySide2.QtWidgets import QWidget
from PySide2.QtCore import Qt
from PySide2.QtWidgets import QGridLayout
from PySide2.QtWidgets import QLineEdit
from PySide2.QtWidgets import QPushButton
from PySide2.QtWidgets import QVBoxLayout
from functools import partial
ERROR_MSG = 'ERROR'
# Create a subclass of QMainWindow to setup the calculator's GUI
class PyCalcUi(QMainWindow):
"""PyCalc's View (GUI)."""
def __init__(self):
"""View initializer."""
super().__init__()
# Set some main window's properties
self.setWindowTitle('PyCalc')
self.setFixedSize(235, 235)
# Set the central widget and the general layout
self.generalLayout = QVBoxLayout()
self._centralWidget = QWidget(self)
self.setCentralWidget(self._centralWidget)
self._centralWidget.setLayout(self.generalLayout)
# Create the display and the buttons
self._createDisplay()
self._createButtons()
def _createDisplay(self):
"""Create the display."""
# Create the display widget
self.display = QLineEdit()
# Set some display's properties
self.display.setFixedHeight(35)
self.display.setAlignment(Qt.AlignRight)
self.display.setReadOnly(True)
# Add the display to the general layout
self.generalLayout.addWidget(self.display)
def _createButtons(self):
"""Create the buttons."""
self.buttons = {}
buttonsLayout = QGridLayout()
# Button text | position on the QGridLayout
buttons = {'7': (0, 0),
'8': (0, 1),
'9': (0, 2),
}
# Create the buttons and add them to the grid layout
for btnText, pos in buttons.items():
self.buttons[btnText] = QPushButton(btnText)
self.buttons[btnText].setFixedSize(40, 40)
buttonsLayout.addWidget(self.buttons[btnText], pos[0], pos[1])
self.mybutton = QPushButton("5")
buttonsLayout.addWidget(self.mybutton,1,0)
# Add buttonsLayout to the general layout
self.generalLayout.addLayout(buttonsLayout)
# Create a Controller class to connect the GUI and the model
class PyCalcCtrl:
"""PyCalc Controller class."""
def __init__(self, model, view):
"""Controller initializer."""
self._evaluate = model
self._view = view
# Connect signals and slots
self._connectSignals()
def _printthis(self):
print("Hi")
def _printthat(self, buttonvalue):
print(buttonvalue)
def _connectSignals(self):
"""Connect signals and slots."""
self._view.mybutton.clicked.connect(self._printthis)
for btnText, btn in self._view.buttons.items():
btn.clicked.connect(partial(self._printthat, btnText))
# Create a Model to handle the calculator's operation
def evaluateExpression(expression):
"""Evaluate an expression."""
try:
result = str(eval(expression, {}, {}))
except Exception:
result = ERROR_MSG
return result
# Client code
def main():
"""Main function."""
# Create an instance of QApplication if it doesn't exist
pycalc = QApplication.instance()
if pycalc is None:
pycalc = QApplication(sys.argv)
# Show the calculator's GUI
view = PyCalcUi()
view.show()
# Create instances of the model and the controller
model = evaluateExpression
PyCalcCtrl(model=model, view=view)
# Execute the calculator's main loop
sys.exit(pycalc.exec_())
if __name__ == '__main__':
main()
This set of code works, BUT if I comment out the
for btnText, btn in self._view.buttons.items():
btn.clicked.connect(partial(self._printthat, btnText))
The self._view.mybutton.clicked.connect(self._printthis) will no longer work.
What is the btn.clicked.connect(partial(self._printthat, btnText)) line doing which is allowing any other signal I put in def _connectSignals(self): to work. What aspect of that line is achieving something that the mybutton signal isn't doing?
The problem is caused because the PyCalcCtrl object is not assigned to a variable so it will be destroyed and therefore the "_printthis" method will not be accessible. On the other hand, when functools.partial is used then the object of the PyCalcCtrl class is assigned to the scope of that function, that's why it works.
The solution is to assign the PyCalcCtrl object to a variable:
ctrl = PyCalcCtrl(model=model, view=view)

unable to re-open a window on pyqt5 pyqtlet

I have a basic GUI window, created with pyqt5 package, that contain a button that once clicked opens a map window thanks to Python's pyqtlet package.
My program does open the map window on first click, but here my issue:
If I close the map window and click again on the button it only show me a white window.
SOURCE CODE
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QGridLayout
from PyQt5.QtCore import Qt
from pyqtlet import L, MapWidget
class MainWindow(QWidget):
def __init__(self):
super().__init__()
# set window title
self.setWindowTitle('Windowtitle')
# set layout
self.layout = QGridLayout()
self.layout.setAlignment(Qt.AlignCenter)
# create button to show the map
self.show_map_button = QPushButton('Show Map')
self.show_map_button.clicked.connect(self.show_map)
# add button to layout
self.layout.addWidget(self.show_map_button, 0, 1)
# show layout
self.setLayout(self.layout)
self.my_map = None
def show_map(self):
# create map window instance
self.my_map = MapWindow()
class MapWindow(QWidget):
def __init__(self):
# Setting up the widgets and layout
super().__init__()
self.mapWidget = MapWidget()
self.layout = QGridLayout()
self.layout.addWidget(self.mapWidget)
self.setLayout(self.layout)
# Working with the maps with pyqtlet
self.map = L.map(self.mapWidget)
self.map.setView([12.97, 77.59], 10)
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png').addTo(self.map)
self.marker = L.marker([12.934056, 77.610029])
self.marker.bindPopup('Maps are a treasure.')
self.map.addLayer(self.marker)
self.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
I click the button for the first time (works as expected):
The second time I click it doesn't work as expected:
Please, can you help me find out where the issue is?
You are not trying to reopen the window but you are creating a new window but pyqtleft only allows you to register a "map" object. So if you want to reopen the window after the user closed it then check that if the object exists then just use the show method:
def show_map(self):
if self.my_map is None:
# create map window instance
self.my_map = MapWindow()
else:
self.my_map.show()

pyside QPushButton setCheckable

I would like to create a QPushButton that stays pressed until the user presses it again. I know I can use setCheckable for this. But I am unsure how to create a proper signal for the button that is triggered when the button changes state, pressed and unpressed. Toggled seems to work, but it is sending 3 arguments. I am unsure what the 3 args being sent are in my example.
import maya.cmds as cmds
import os
import maya.OpenMayaUI as mui
from PySide2 import QtWidgets,QtCore,QtGui
import shiboken2
class widget():
def __init__(self):
self.objs = ["box_1","box_2","box_3"]
def label_event(self,text):
print("this is the pressed button's label", text)
def populate(self):
for obj in self.objs:
label = QtWidgets.QPushButton(obj)
label.setCheckable(True)
label.toggled.connect(partial(self.label_event, obj))
self.vertical_layout_main.addWidget(label)
def palette_ui(self):
windowName = "palette"
if cmds.window(windowName,exists = True):
cmds.deleteUI(windowName, wnd = True)
pointer = mui.MQtUtil.mainWindow()
parent = shiboken2.wrapInstance(long(pointer),QtWidgets.QWidget)
self.window = QtWidgets.QMainWindow(parent)
self.window.setObjectName(windowName)
self.window.setWindowTitle(windowName)
self.mainWidget = QtWidgets.QWidget()
self.window.setCentralWidget(self.mainWidget)
self.vertical_layout_main = QtWidgets.QVBoxLayout(self.mainWidget)
self.populate()
self.window.setAttribute(QtCore.Qt.WA_DeleteOnClose)
self.window.show()
lg = widget()
lg.palette_ui()
You have to activate the property with setCheckable(True) and use the toggled signal:
import sys
from PySide import QtGui
def function(checked):
print("is checked?: ", checked)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
button = QtGui.QPushButton("press me")
button.setCheckable(True)
button.toggled.connect(function)
button.show()
sys.exit(app.exec_())
Update:
Do not use object is a reserved word, on the other hand the signal passes the parameter checked, if you want to pass another parameter you must also place it in the function:
def label_event(self, text, checked): # <---
print("this is the pressed button's label", text, checked)
def populate(self):
for obj in self.objects:
label = QtWidgets.QPushButton(obj)
label.setCheckable(True)
label.toggled.connect(partial(self.label_event, obj))
self.vertical_layout_main.addWidget(label)

How can I add a submit, output and input box using PyQt4?

I never tried creating a GUI with a language other than Java(kinda left it aside not long ago)
and started using Python.
made a simple program that calculates Pi to a certain digit as the user wishes.
Now, I created a window with PyQt4, made a button and got everything in place.
How can I add a input box so that the user could enter a number into it, make the button "Enter" the information and at the end of all that output it to the window instead of the terminal?
That's what I've got for now:
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
from decimal import *
class Window(QtGui.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(50, 50, 800, 600)
self.setWindowTitle("Pi's Nth Digit")
self.setWindowIcon(QtGui.QIcon('icon.jpg'))
self.buttons()
def buttons(self):
btn = QtGui.QPushButton("Quit",self)
btn1 = QtGui.QPushButton("Get Pi",self)
btn.clicked.connect(QtCore.QCoreApplication.instance().quit)
btn1.clicked.connect(self.getpi())
btn1.resize(btn1.sizeHint())
btn.resize(btn.sizeHint())
btn1.move(350,500)
btn.move(450,500)
self.show()
def start():
app = QtGui.QApplication(sys.argv)
GUI = Window()
sys.exit(app.exec_())
start()
don't mind the getpi function.
Thanks! :)
You would want to use a QLineEdit or a QSpinBox for a number. If you want multiple things in a widget you would use a layout. A QMainWindow typically has one central widget and toolbars and dock widgets.
class Window(QtGui.QMainWindow):
def __init__(self):
super().__init__()
self.container = QtGui.QWidget()
self.setCentralWidget(self.container)
self.container_lay = QtGui.QVBoxLayout()
self.container.setLayout(self.container_lay)
# Input
self.le = QtGui.QLineEdit()
self.container_lay.addWidget(self.le)
# enter button
self.enter_btn = QtGui.QPushButton("Enter")
self.container_lay.addWidget(self.enter_btn)
self.enter_btn.clicked.connect(self.run) # No '()' on run you want to reference the method.
# display
self.container_lay.addWidget(QtGui.QLabel("Answer:"))
self.ans = QtGui.QLabel()
self.container_lay.addWidget(self.ans)
def run(self):
precision = self.le.text()
pi = str(round(math.pi, precision)) # probably different formatting
self.ans.setText(pi)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
You have almost everything, just add a QLineEdit to get the input and a QLabel where to show the result (with QLabel.setText).

how to use blocking MessgeBox in kivy

I have a Kivy application.
From the main GUI, I want to open a new message box and force the main GUI to await the result of an action box interaction.
I saw that Qt4 message box has support for this blocking call type, but I haven't found the equivalent functionality in Kivy. Does such a feature exist?
The Popup widget is used to create modal popups. By default, the popup will cover the whole “parent” window. When you are creating a popup, you must at a minimum set a Popup.title and a Popup.content widget.
modal means blocking :)
http://kivy.org/docs/api-kivy.uix.popup.html
Here is a code snippet which does the job though it is actually not really blocking.
You need to define one or two alternatives to jump to in order to continue working with
the program. Thats the pseudo-blocking trick.
import kivy
from kivy.uix.popup import Popup
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.app import App
class MessageBoxApp(App):
def build(self):
return Button(text='Press for MessageBox!', on_press=self.callpopup)
def callpopup(self, event):
dlg = MessageBox(self, titleheader="Title Header", message="Any Message",
options={"YES": "printyes()", "NO": "printno()", "CANCEL": ""})
print "Messagebox shows as kivy popup and we wait for the user action"
def printyes(self):
# routine for going yes
print "You chose the Yes routine"
def printno(self):
# routine for going no
print "You chose the No routine"
class MessageBox(MessageBoxApp):
def __init__(self, parent, titleheader="Title", message="Message", options={"OK": ""}, size=(400, 400)):
def popup_callback(instance):
"callback for button press"
self.retvalue = instance.text
self.popup.dismiss()
self.parent = parent
self.retvalue = None
self.titleheader = titleheader
self.message = message
self.options = options
self.size = size
box = GridLayout(orientation='vertical', cols=1)
box.add_widget(Label(text=self.message, font_size=16))
b_list = []
buttonbox = BoxLayout(orientation='horizontal')
for b in self.options:
b_list.append(Button(text=b, size_hint=(1,.35), font_size=20))
b_list[-1].bind(on_press=popup_callback)
buttonbox.add_widget(b_list[-1])
box.add_widget(buttonbox)
self.popup = Popup(title=titleheader, content=box, size_hint=(None, None), size=self.size)
self.popup.open()
self.popup.bind(on_dismiss=self.OnClose)
def OnClose(self, event):
self.popup.unbind(on_dismiss=self.OnClose)
self.popup.dismiss()
if self.retvalue != None and self.options[self.retvalue] != "":
command = "self.parent."+self.options[self.retvalue]
exec command
if __name__ == '__main__':
MessageBoxApp().run()

Categories