roman = {1: 'I', 2: 'II', 3: 'III', 4: 'IV', 5: 'V'}
arabic = {'I': 1, 'II': 2, 'III': 3, 'IV': 4, 'V': 5}
class Numbers:
@staticmethod
def to_roman(integer: int)->str:
return roman[integer]
@staticmethod
def to_arabic(string: str)->int:
return arabic[string]
def test():
print(Numbers.to_arabic('V'))
print(Numbers.to_roman(3))
if __name__ == '__main__':
test() from time import sleep
import keyboard
def print_pressed_keys(event):
with open('data.txt', 'a') as file:
file.write(f"{event} {event.name}\n")
try:
keyboard.hook(print_pressed_keys)
keyboard.wait()
except KeyboardInterrupt:
print('\nПрограмма остановленна пользователем!')
sleep(1.5)from datetime import datetime
from tkinter import *
from functools import partial
root = Tk()
root.title("Запись давления")
root.geometry('300x200+200+200')
pressure = StringVar()
pulse = StringVar()
datetime = datetime.now()
lbl1 = Label(root,text="Давление")
ent1 = Entry(textvariable=pressure, font=17)
lbl2 = Label(root,text="Пульс")
ent2 = Entry(textvariable=pulse, font=17)
lbl1.pack()
ent1.pack()
lbl2.pack()
ent2.pack()
def write(pulse, pressure, datetime):
with open("pulse.txt", "w") as file:
data = "Время: {0}\nПульс: {1}\nДавление: {2}".format(datetime, pulse.get(), pressure.get())
file.write(data)
butt = Button(root,text="Записать", command=partial(write, pressure, pulse, datetime))
butt.pack()
root.mainloop()
from kivy.lang import Builder
from kivymd.app import MDApp
KV = '''
BoxLayout:
padding: "10dp"
MDRaisedButton:
id: button_show_text
on_press: app.show_text()
MDTextField:
id: text_field
hint_text: "Helper text on error (press 'Enter')"
helper_text: "There will always be a mistake"
helper_text_mode: "on_error"
pos_hint: {"center_y": .5}
'''
class Test(MDApp):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.screen = Builder.load_string(KV)
def build(self):
self.screen.ids.text_field.bind(
on_text_validate=self.set_error_message,
on_focus=self.set_error_message,
)
return self.screen
def set_error_message(self, instance_text_field):
self.screen.ids.text_field.error = True
def show_text(self):
print(self.screen.ids.text_field.text)
Test().run()
from subprocess import Popen, PIPE, DEVNULL, STDOUT
from time import sleep
list_argumrnts = ['ping', 'www.google.com']
with Popen(list_argumrnts, stdout=PIPE, stdin=DEVNULL, stderr=STDOUT, encoding='cp866') as process:
for line in iter(process.stdout.readline, b''):
sleep(0.1)
print(line.rstrip('\n'))
if line == '':
break import pickle
def main():
array = ['123', '456', '789']
with open('data.pickle', 'wb') as file:
pickle.dump(array, file)
with open('data.pickle', 'rb') as file:
array = pickle.load(file)
print(array)
if __name__ == '__main__':
main()import os
import sys
from io import BytesIO
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout
from PyQt5.QtWidgets import QLabel, QPushButton, QMessageBox
from PyQt5.QtGui import QPixmap, QImage
import requests
url = """https://3.bp.blogspot.com/-rDqzMGTOAzI/U0Uj\
-HQauwI/AAAAAAAAB1c/4YfKMvqN_wk/s1600/%D0%94%D0%B0%D0\
%B2%D0%B0%D0%B9+%D1%8F+%D0%BF%D0%BE%D0%B8%D1%89%D1%83+\
%D0%B2+Google+%D0%B7%D0%B0+%D1%82%D0%B5%D0%B1%D1%8F.png
"""
# Отловить ошибки в слотах PyQt5
def log_uncaught_exceptions(ex_cls, ex, tb):
text = '{}: {}:\n'.format(ex_cls.__name__, ex)
import traceback
text += ''.join(traceback.format_tb(tb))
print(text)
QMessageBox.critical(None, 'Упс( Ошибочка...', text)
quit()
sys.excepthook = log_uncaught_exceptions
class WindowsApplication(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle('Супер приложение')
self.setGeometry(300, 200, 800, 600)
vbox = QVBoxLayout(self)
label = QLabel()
button = QPushButton(text='Сделать снимок приложения')
button.clicked.connect(self.buttonHandler)
vbox.addWidget(label)
vbox.addWidget(button)
content = requests.get(url).content
pixmap = QPixmap()
pixmap.loadFromData(content)
label.setPixmap(pixmap)
def buttonHandler(self):
grab = self.grab()
grab.save('image.png', 'png')
os.startfile('image.png')
print('END')
def main():
application = QApplication(sys.argv)
main_window = WindowsApplication()
main_window.show()
sys.exit(application.exec_())
if __name__ == '__main__':
main() ImportError: cannot import name 'init' from partially initialized module 'colorama' (most likely due
to a circular import)from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from random import random
from kivy.core.window import Window
from kivy.graphics import (Color, Ellipse, Rectangle, Line)
class PainterWidget(Widget):
r, g, b = (255, 255, 255)
def on_touch_down(self, touch):
with self.canvas:
self.touch = touch
self.configure()
def on_touch_move(self, touch):
touch.ud['line'].points += (touch.x, touch.y)
def configure(self):
Color(self.r, self.g, self.b, 1)
rad = 15
Ellipse(pos = (self.touch.x - rad/2,self.touch.y - rad/2), size = (rad, rad))
self.touch.ud['line'] = Line(points = (self.touch.x, self.touch.y), width = 15)
def changeColor(self, rgb):
self.r, self.g, self.b = rgb
class PaintApp(App):
def build(self):
parent = Widget()
self.painter = PainterWidget()
parent.add_widget(self.painter)
parent.add_widget(Button(text = 'Clear' , on_press = self.clear_canvas, size = (100, 50)))
parent.add_widget(Button(text = 'Save' , on_press = self.save, size = (100, 50), pos = (100, 0)))
parent.add_widget(Button(text = 'Screen', on_press = self.screen, size = (100, 50), pos=(200, 0 )))
parent.add_widget(Button(text = 'red', on_press = self.red, size = (100, 50), pos=(300, 0 )))
parent.add_widget(Button(text = 'green', on_press = self.green, size = (100, 50), pos=(400, 0 )))
parent.add_widget(Button(text = 'blue', on_press = self.blue, size = (100, 50), pos=(500, 0 )))
return parent
def red(self, instance):
self.painter.changeColor(rgb=(255, 0, 0))
def green(self, instance):
self.painter.changeColor(rgb=(0, 255, 0))
def blue(self, instance):
self.painter.changeColor(rgb=(0, 0, 255))
def clear_canvas(self, instance):
self.painter.canvas.clear()
def save(self, instance):
self.painter.size = (Window.size[0], Window.size[1])
self.painter.export_to_png('mage.png')
def screen(self, instance):
Window.screenshot('screen.png')
if __name__ == '__main__':
PaintApp().run()
import sys
import random
import matplotlib
matplotlib.use('Qt5Agg')
from PyQt5 import QtCore, QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
class MplCanvas(FigureCanvas):
def __init__(self, parent=None, width=5, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111)
super(MplCanvas, self).__init__(fig)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.canvas = MplCanvas(self, width=5, height=4, dpi=100)
self.setCentralWidget(self.canvas)
n_data = 50
self.xdata = list(range(n_data))
self.ydata = [random.randint(0, 10) for i in range(n_data)]
self.update_plot()
self.show()
# Setup a timer to trigger the redraw by calling update_plot.
self.timer = QtCore.QTimer()
self.timer.setInterval(100)
self.timer.timeout.connect(self.update_plot)
self.timer.start()
def update_plot(self):
# Drop off the first y element, append a new one.
self.ydata = self.ydata[1:] + [random.randint(0, 10)]
self.canvas.axes.cla() # Clear the canvas.
self.canvas.axes.plot(self.xdata, self.ydata, 'r')
# Trigger the canvas to update and redraw.
self.canvas.draw()
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
app.exec_() import sys
import numpy
import cv2
from PyQt5.QtWidgets import QWidget, QApplication, QMessageBox
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtGui import QPixmap, QPalette, QBrush, QImage
from PIL import Image, ImageDraw, ImageQt
# Отловить ошибки в слотах PyQt5
def log_uncaught_exceptions(ex_cls, ex, tb):
text = '{}: {}:\n'.format(ex_cls.__name__, ex)
import traceback
text += ''.join(traceback.format_tb(tb))
print(text)
QMessageBox.critical(None, 'Error', text)
quit()
sys.excepthook = log_uncaught_exceptions
class TransparentWindow(QWidget):
def __init__(self):
super().__init__()
self.interface()
def interface(self):
self.setWindowFlags(Qt.Window | Qt.FramelessWindowHint)
self.setWindowFlag(Qt.WindowStaysOnTopHint)
pil_image = Image.new('RGBA', (300, 300), (0, 0, 0, 0))
draw = ImageDraw.Draw(pil_image)
draw.rectangle((0, 0, 300, 300), outline=(0, 0, 255), width=5)
numpy_array = numpy.array(pil_image)
opencv_image = cv2.cvtColor(numpy_array, cv2.COLOR_RGBA2BGRA)# cv2.COLOR_BGR2HSV
# Start coordinate, here (5, 5)
# represents the top left corner of rectangle
start_point = (5, 5)
# Ending coordinate, here (220, 220)
# represents the bottom right corner of rectangle
end_point = (220, 220)
# Blue color in BGRA
color = (0, 0, 255, 255)
# Line thickness of 2 px
thickness = 2
# Using cv2.rectangle() method
# Draw a rectangle with blue line borders of thickness of 2 px
image = cv2.rectangle(opencv_image, start_point, end_point, color, thickness)
# Конвертируем изображение из OpenCV в PIL
pil_image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGRA2RGBA))
image_qt = ImageQt.toqimage(pil_image)
pixmap = QPixmap.fromImage(image_qt)
palette = self.palette()
palette.setBrush(QPalette.Normal, QPalette.Window, QBrush(pixmap))
palette.setBrush(QPalette.Inactive, QPalette.Window, QBrush(pixmap))
self.setPalette(palette)
self.setMask(pixmap.mask())
def drag_window(self, event):
delta = QPoint(event.globalPos() - self.old_position)
self.move(self.x() + delta.x(), self.y() + delta.y())
self.old_position = event.globalPos()
def mousePressEvent(self, event):
"""Выбрать окно при помощи мыши"""
self.old_position = event.globalPos()
self.old_position = event.globalPos()
def mouseMoveEvent(self, event):
"""Переместить окно с помощью мыши"""
self.drag_window(event)
x, y = self.get_window_coordinates()
width, height = self.get_window_size()
region = x, y, width, height
def get_window_size(self):
"""Вернёт кортеж(width, height) размер окна"""
size = self.frameSize().width(), self.frameSize().height()
return size
def get_window_coordinates(self):
"""Вернёт кортеж(x, y) координаты окна"""
coordinates = self.x(), self.y()
return coordinates
def main():
application = QApplication(sys.argv)
transparent_window = TransparentWindow()
transparent_window.show()
sys.exit(application.exec_())
if __name__ == '__main__':
main() from subprocess import Popen, PIPE
def get_ping():
args = ["ping", "-n", "4", "www.ya.ru"] # -n требуются права Администратора
process = Popen(args, stdout=PIPE)
"""
# Построчное чтение данных
for line in process.stdout:
print("stdout:", line.decode('cp866'))
"""
data, error = process.communicate() # Распаковка кортежа
print(error)
return data.decode(encoding='cp866') # cp866 для Windows
def main():
print(get_ping())
input()
if __name__ == '__main__':
main()