from threading import Thread
import time
from pynput import keyboard
def on_press(key):
try:
print('alphanumeric key {0} pressed'.format(
key.char))
except AttributeError:
print('special key {0} pressed'.format(
key))
def on_release(key):
print('{0} released'.format(
key))
if key == keyboard.Key.esc:
# Stop listener
return False
def listener():
# Collect events until released
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
def main():
for i in range(10):
time.sleep(1)
print(i)
if __name__ == '__main__':
th = Thread(target=listener)
th.start()
main()
import sys
from PyQt5.QtWidgets import (QWidget, QApplication, QPushButton, QSlider,
QVBoxLayout, QMessageBox)
from PyQt5.QtCore import Qt
class QButtonExample(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 200, 150)
self.button = QPushButton(self, text="Ты не сможешь на меня нажать!")
self.button.setEnabled(False)
self.button.clicked.connect(self.handleButton)
slider = QSlider(Qt.Horizontal, self)
slider.setFocusPolicy(Qt.NoFocus)
slider.setGeometry(30, 40, 100, 30)
slider.valueChanged[int].connect(self.changeValue)
boxLayout = QVBoxLayout(self)
# boxLayout.addStretch(1)
boxLayout.addWidget(self.button)
boxLayout.addWidget(slider)
def changeValue(self, value):
if value > 50:
self.button.setEnabled(True)
else:
self.button.setEnabled(False)
def handleButton(self):
QMessageBox.information(None, 'Сообщение от программы', "Да ладно! у тебя получилось!")
if __name__ == '__main__':
app = QApplication(sys.argv)
myApplication = QButtonExample()
myApplication.show()
sys.exit(app.exec_())
import psutil
user_commands = ""
while user_commands != "Выйти":
user_commands = input("Введите команду -->")
if user_commands == "Диагностика компьютера":
print("ЦП: {0}".format(psutil.cpu_percent()))
print("Память всего: {0}, занято: {1} %".format(psutil.virtual_memory()[0], psutil.virtual_memory()[2]))
from tkinter import Tk, Entry, Checkbutton, mainloop
class Example(Tk):
def __init__(self):
super().__init__()
self.input_field_1 = Entry(self)
self.input_field_1.grid(row=0, column=0)
self.check_button_1 = Checkbutton(self)
self.check_button_1.grid(row=0, column=1)
self.input_field_2 = Entry(self)
self.input_field_2.grid(row=1, column=0)
self.check_button_2 = Checkbutton(self, command=self.disable_or_normal_input_field_2)
self.check_button_2.grid(row=1, column=1)
def disable_or_normal_input_field_2(self):
if self.input_field_2['state'] == 'normal':
self.input_field_2.configure(state="disable")
else:
self.input_field_2.configure(state="normal")
print("Поле ввода 2 статус:", self.input_field_2['state'])
def main():
example = Example()
example.mainloop()
if __name__ == '__main__':
main()
import requests
from bs4 import BeautifulSoup
def get_html(site):
r = requests.get(site)
return r.text
def get_page_data(html): #sources
soup = BeautifulSoup(html, 'lxml') #(format_in, parser)
line = soup.find('table', id='theProxyList').find_all('tr') #resolve table
for tr in line:
td = tr.find_all('td')
if td == []:
continue
ip = td[1].text
port = td[2].text
country = td[3].text
anonym = td[4].text
types = td[5].text
time = td[6].text
data = {'ip': ip,
'Port': port,
'Country': country,
'Anonymize': anonym,
'Type': types,
'Time': time}
print(data)
def main():
url = 'http://foxtools.ru/Proxy'
get_page_data(get_html(url))
if __name__ == '__main__':
main()
import io
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import requests
def log_uncaught_exceptions(ex_cls, ex, tb):
text = '{}: {}:\n\n'.format(ex_cls.__name__, ex)
import traceback
text += ''.join(traceback.format_tb(tb))
QMessageBox.critical(None, 'Ошибка!', text)
quit()
sys.excepthook = log_uncaught_exceptions
class SenderMessage(QObject):
image_bytes = pyqtSignal(bytes)
def __init__(self):
super().__init__()
@pyqtSlot()
def run(self):
image_bytes = requests.get('https://dadaviz.ru/wp-content/uploads/2018/02/1-12.jpg', stream=True).content
self.image_bytes.emit(image_bytes)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle("Показать изображение")
self.setGeometry(400, 200, 626, 626)
self.label_image = QLabel(self)
self.label_image.setGeometry(0, 0, 626, 626)
self.pixmap = QPixmap()
self.thread = QThread()
self.sender_message = SenderMessage()
self.sender_message.moveToThread(self.thread)
self.sender_message.image_bytes.connect(self.signalHandlerImageBytes)
self.thread.started.connect(self.sender_message.run)
self.thread.start()
def signalHandlerImageBytes(self, image_bytes):
self.pixmap.loadFromData(image_bytes)
self.label_image.setPixmap(self.pixmap)
def main():
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
from tkinter import Tk, Button, Label, LabelFrame, mainloop
from functools import partial
SIGNAL = int
class App(Tk):
normal_engine_speed = 1500
def __init__(self):
super().__init__()
self.interface()
def interface(self):
self.title("Управление станком")
self["bg"] = "gray22"
self.geometry("300x150+500+300")
self.resizable(False, False)
title_label = Label(self, text="Обороты двигателя")
title_label.config(font="Times 18 bold", fg="green")
title_label.place(x=40)
button_reduce_speed = Button(self, text="-10")
button_reduce_speed.config(font="Times 13 bold", fg="blue")
button_reduce_speed.bind('<Button-1>', partial(self.button_click_handler, 0))
button_reduce_speed.place(x=0, y=0)
button_add_speed = Button(self, text="+10")
button_add_speed.config(font="Times 13 bold", fg="blue")
button_add_speed.bind('<Button-1>', partial(self.button_click_handler, 1))
button_add_speed.place(x=261, y=0)
self.show_engine_speed = Label(self, text=self.normal_engine_speed)
self.show_engine_speed.config(font="Times 30 bold", bg="black", fg="green")
self.show_engine_speed.config(width=13, height=2)
self.show_engine_speed.place(y=40)
def button_click_handler(self, SIGNAL, event):
if SIGNAL == 0:
self.normal_engine_speed -= 10
elif SIGNAL == 1:
self.normal_engine_speed += 10
self.show_engine_speed["text"] = self.normal_engine_speed
if __name__ == "__main__":
app = App()
app.mainloop()
import sys
import numpy
from PIL import Image
from PIL.ImageQt import ImageQt
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QMessageBox
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtCore import Qt
def log_uncaught_exceptions(ex_cls, ex, tb):
text = '{}: {}:\n\n'.format(ex_cls.__name__, ex)
import traceback
text += ''.join(traceback.format_tb(tb))
QMessageBox.critical(None, 'Ошибка!', text)
quit()
sys.excepthook = log_uncaught_exceptions
class ShowImage(QMainWindow):
def __init__(self):
super().__init__()
self.interface()
def interface(self):
self.setWindowTitle("Пример рисования изображения")
self.setGeometry(400, 200, 600, 400)
pixel = numpy.zeros((10, 10, 3)).astype(int)
pixel[0][0][2] = 255
print(pixel)
image = Image.fromarray(pixel, 'RGB')
self.image_qt = ImageQt(image)
pixmap = QPixmap(QImage(self.image_qt))
label = QLabel(self)
label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
label.setStyleSheet("background-color: white")
label.setGeometry(0, 0, 100, 100)
label.setPixmap(pixmap)
if __name__ == "__main__":
app = QApplication(sys.argv)
my_application = ShowImage()
my_application.show()
sys.exit(app.exec_())
from tkinter import *
import pyautogui as pag
class AutoTap(Tk):
def __init__(self):
super().__init__()
self.button = Button(self, text="кнопка")
self.button.config(command=self.signal_handler, width=15)
self.button.pack()
self.label = Label(self)
self.label.pack()
self.auto_tap()
def signal_handler(self):
self.label["text"] = "нажата кнопка{0}".format(str(self.button.winfo_rootx()))
def auto_tap(self):
pag.click(self.button.winfo_rootx()+5, self.button.winfo_rooty()+5)
self.after(5000, self.auto_tap)
app = AutoTap()
app.mainloop()
from random import randint
from tkinter import Tk, Label, mainloop
from time import sleep
class App(Tk):
def __init__(self):
super().__init__()
self.label = Label(self)
self.label.pack()
self.run()
def run(self):
self.label["text"] = str(randint(1, 10000))
self.after(1000, self.run)
app = App()
app.mainloop()
from time import sleep
import webbrowser
def dialog():
print("Привет!")
while True: # Бесконечный цикл пока не будет вызвана инструкция break
user = input("--> ")
if user == "привет":
print("Как дела?")
elif user == "отлично":
print("Молодец, так держать!")
break
elif user == "хорошо":
print("Я за тебя рад!")
break
elif user == "не очень":
print("А что случилось?")
user = input("--> ")
if user == "не могу выстроить логическую цепочку":
print("Одну минуточку...")
sleep(3)
webbrowser.open("https://pythonworld.ru/osnovy/instrukciya-if-elif-else-proverka-istinnosti-trexmestnoe-vyrazhenie-ifelse.html")
else:
break
input("Программа завершила свою работу для выхода нажмите Enter")
dialog()