🔺️Тест на IQ с помощью python
Исходный код:
Результат: https://www.tiktok.com/t/ZTFc3kWgW/
Исходный код:
import tkinter as tk
from tkinter import messagebox
questions = [
{
"question": "Какое число должно быть следующим в ряду: 2, 4, 8, 16?",
"options": ["32", "24", "20", "18"],
"answer": "32"
},
{
"question": "Найдите лишнее слово: Кошка, Собака, Ягода, Курица",
"options": ["Кошка", "Собака", "Ягода", "Курица"],
"answer": "Ягода"
},
{
"question": "Продолжите последовательность: 1, 1, 2, 3, 5, 8, ?",
"options": ["10", "12", "13", "21"],
"answer": "13"
},
{
"question": "Сколько букв в русском алфавите?",
"options": ["30", "31", "32", "33"],
"answer": "33"
},
{
"question": "Как называется фигура с 8 сторонами?",
"options": ["Гексагон", "Гептагон", "Октагон", "Декагон"],
"answer": "Октагон"
}
]
class IQTestApp:
def init(self, root):
self.root = root
self.root.title("IQ Test")
self.score = 0
self.current_question = 0
self.setup_ui()
def setup_ui(self):
self.question_label = tk.Label(self.root, text="", wraplength=400, font=("Arial", 14))
self.question_label.pack(pady=20)
self.option_buttons = []
for i in range(4):
btn = tk.Button(self.root, text="", width=30, command=lambda idx=i: self.check_answer(idx))
btn.pack(pady=5)
self.option_buttons.append(btn)
self.next_button = tk.Button(self.root, text="Следующий вопрос", command=self.next_question)
self.next_button.pack(pady=20)
self.display_question()
def display_question(self):
q = questions[self.current_question]
self.question_label.config(text=q["question"])
for i, option in enumerate(q["options"]):
self.option_buttons[i].config(text=option)
def check_answer(self, selected_idx):
selected_option = questions[self.current_question]["options"][selected_idx]
if selected_option == questions[self.current_question]["answer"]:
self.score += 1
self.next_question()
def next_question(self):
self.current_question += 1
if self.current_question < len(questions):
self.display_question()
else:
iq_score = 80 + self.score * 10
messagebox.showinfo("Результат", f"Вы ответили правильно на {self.score} из {len(questions)} вопросов.\nВаш IQ: {iq_score}")
self.root.quit()
root = tk.Tk()
app = IQTestApp(root)
root.mainloop()
Результат: https://www.tiktok.com/t/ZTFc3kWgW/
👍5❤2🔥2
〽️ Анимированный текст с помощью python
Исходный код:
Пример анимации в ролике: https://vt.tiktok.com/ZSjA7c9TW/
Исходный код:
import pygame
import time
WIDTH, HEIGHT = 800, 200
text = 'Любой текст'
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
font = pygame.font.Font(None, 50)
clock = pygame.time.Clock()
displayed_text = ''
i = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if i < len(text):
displayed_text += text[i]
i += 1
screen.fill((0, 0, 0))
rendered_text = font.render(displayed_text, True, (255, 255, 255))
screen.blit(rendered_text, (50, HEIGHT // 2))
pygame.display.flip()
time.sleep(0.1)
clock.tick(30)
pygame.quit()
Пример анимации в ролике: https://vt.tiktok.com/ZSjA7c9TW/
❤🔥4👍1 1
🎦 Программа для записи экрана на python
Исходный код:
Пример записи в ролике: https://vt.tiktok.com/ZSjPPwV5h/
Исходный код:
import cv2
import numpy as np
import pyautogui
def record_screen(output_file='video.mp4', fps=20.0):
screen_size = pyautogui.size()
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(output_file, fourcc, fps, screen_size)
print("Запись началась. Нажмите 'q', чтобы остановить.")
while True:
screenshot = pyautogui.screenshot()
frame = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)
cv2.imshow("Recording...", frame)
out.write(frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
print("Запись завершена")
break
out.release()
cv2.destroyAllWindows()
if name == "main":
record_screen()
Пример записи в ролике: https://vt.tiktok.com/ZSjPPwV5h/
👍3❤1❤🔥1🔥1
♻️ Скриншот экрана с помощью python
Исходный код:
Ссылка на ролик: https://vt.tiktok.com/ZSjH1XyTf/
Исходный код:
import tkinter as tk
from tkinter import messagebox
import pyautogui
def take_screenshot():
try:
filename = "screenshot.png"
screenshot = pyautogui.screenshot()
screenshot.save(filename)
messagebox.showinfo(f"Скриншот сохранен как {filename}")
except Exception as e:
messagebox.showerror("Ошибка", f"Не удалось сделать скриншот: {e}")
root = tk.Tk()
root.title("Скриншотер")
root.geometry("300x200")
btn_screenshot = tk.Button(root, text="Скрин", command=take_screenshot, font=("Arial", 24), bg="lightblue", width=10, height=2)
btn_screenshot.pack(pady=50)
root.mainloop()
Ссылка на ролик: https://vt.tiktok.com/ZSjH1XyTf/
❤4👍1
▪️Проверка надёжности пароля на python
Исходный код:
Ссылка на ролик: https://vt.tiktok.com/ZSjQNQAkF/
Исходный код:
import re
def check_password_strength(password):
if len(password) < 8:
return "Пароль слишком короткий. Минимальная длина - 8 символов."
if not re.search(r'[A-Z]', password):
return "Пароль должен содержать хотя бы одну заглавную букву."
if not re.search(r'[a-z]', password):
return "Пароль должен содержать хотя бы одну строчную букву."
if not re.search(r'\d', password):
return "Пароль должен содержать хотя бы одну цифру."
if not re.search(r'[@$!%*?&]', password):
return "Пароль должен содержать хотя бы один специальный символ (например, @$!%*?&)."
common_words = ["password", "123456", "qwerty"]
if any(word in password.lower() for word in common_words):
return "Пароль не должен содержать распространённые слова или последовательности символов."
return "Пароль надежный"
password = input("Введите пароль: ")
result = check_password_strength(password)
print(result)
Ссылка на ролик: https://vt.tiktok.com/ZSjQNQAkF/
👍6❤1🔥1
☢ Спамер на python
Исходный код:
Ссылка на ролик: https://vt.tiktok.com/ZSj4UD7uC/
Исходный код:
from tkinter import *
import time
import pyautogui
import threading
tk = Tk()
tk.geometry('200x200')
tk.title('спамер')
def spam():
while True:
pyautogui.typewrite('77')
pyautogui.press('7')
time.sleep(1)
def start_spam():
thread = threading.Thread(target=spam)
thread.daemon = True
thread.start()
button = Button(tk, text='ЗАПУСК СПАМЕРА', font=('Arial', 14), command=start_spam)
button.pack(pady=20)
tk.mainloop()
Ссылка на ролик: https://vt.tiktok.com/ZSj4UD7uC/
👍3🔥2❤🔥1
⌨ Счётчик нажатий клавиш на python
Исходный код:
Ссылка на ролик: https://vt.tiktok.com/ZSjbs5y5K/
Исходный код:
import tkinter as tk
from pynput import keyboard
class KeyPressCounterApp:
def init(self, root):
self.root = root
self.root.title("Счётчик нажатий клавиш")
self.root.geometry("400x300")
self.key_count = 0
self.label = tk.Label(self.root, text="Нажатий: 0", font=("Arial", 30))
self.label.pack(pady=80)
self.listener = keyboard.Listener(on_press=self.on_key_press)
self.listener.start()
self.root.protocol("WM_DELETE_WINDOW", self.on_close)
def on_key_press(self, key):
self.key_count += 1
self.label.config(text=f"Нажатий: {self.key_count}")
def on_close(self):
self.listener.stop()
self.root.destroy()
if name == "main":
root = tk.Tk()
app = KeyPressCounterApp(root)
root.mainloop()
Ссылка на ролик: https://vt.tiktok.com/ZSjbs5y5K/
👍3❤2
🖱 Программа для теста скорости кликов на python
Исходный код:
Ссылка на ролик: https://vt.tiktok.com/ZSj7JqqK3/
Исходный код:
import tkinter as tk
import time
class ClickSpeedTest:
def init(self, root):
self.root = root
self.root.geometry("500x400")
self.count = 0
self.start_time = None
self.time_limit = 10
self.label = tk.Label(root, text="Быстрее!\n", font=("Arial", 16))
self.label.pack(pady=30)
self.click_button = tk.Button(root, text="Кликай!", font=("Arial", 20), width=10, height=2, command=self.register_click)
self.click_button.pack(pady=20)
self.reset_button = tk.Button(root, text="Начать заново", font=("Arial", 16), width=15, height=2, command=self.reset_test)
self.reset_button.pack(pady=20)
self.time_label = tk.Label(root, text="Время: 0 сек.", font=("Arial", 16))
self.time_label.pack(pady=20)
def register_click(self):
if self.start_time is None:
self.start_time = time.time()
self.time_label.after(1000, self.update_time)
self.count += 1
def update_time(self):
if self.start_time:
elapsed_time = time.time() - self.start_time
remaining_time = max(0, self.time_limit - elapsed_time)
self.time_label.config(text=f"Время: {int(remaining_time)} сек.")
if remaining_time == 0:
self.show_result()
else:
self.time_label.after(1000, self.update_time)
def show_result(self):
self.label.config(text=f"Конец!\nВы сделали {self.count} кликов за {self.time_limit} секунд.")
self.click_button.config(state=tk.DISABLED)
def reset_test(self):
self.count = 0
self.start_time = None
self.label.config(text="Кликай!")
self.time_label.config(text="Время: 0 сек.")
self.click_button.config(state=tk.NORMAL)
root = tk.Tk()
app = ClickSpeedTest(root)
root.mainloop()
Ссылка на ролик: https://vt.tiktok.com/ZSj7JqqK3/
🔥4❤1👍1
📪 Программа для получения информации о почте на python
Исходный код:
Ссылка на ролик: https://vt.tiktok.com/ZSj3XGRhW/
Исходный код:
import dns.resolver
def get_email_info(email):
try:
local_part, domain = email.split('@')
print(f"Локальная часть: {local_part}")
print(f"Домен: {domain}")
print("\nПоиск MX-записей...")
mx_records = dns.resolver.resolve(domain, 'MX')
for mx in mx_records:
print(f" Почтовый сервер: {mx.exchange}, приоритет: {mx.preference}")
print("\nИнформация о домене:")
try:
a_records = dns.resolver.resolve(domain, 'A')
for a in a_records:
print(f" IP-адрес: {a}")
except dns.resolver.NoAnswer:
print(" A-записи не найдены.")
try:
txt_records = dns.resolver.resolve(domain, 'TXT')
for txt in txt_records:
if "v=spf1" in str(txt):
print(f" SPF-запись: {txt}")
except dns.resolver.NoAnswer:
print(" SPF-записи не найдены.")
except Exception as e:
print(f"Ошибка: {e}")
email = input("Введите адрес электронной почты: ")
get_email_info(email)
Ссылка на ролик: https://vt.tiktok.com/ZSj3XGRhW/
👍5❤1
🥚 Убегающее яйцо на python
Исходный код:
Результат в ролике: https://vt.tiktok.com/ZSjKQyw5w/
Исходный код:
import tkinter as tk
import random
WIDTH, HEIGHT = 800, 600
PERSON_WIDTH, PERSON_HEIGHT = 70, 110
BASE_SPEED = 20
root = tk.Tk()
root.title("Убегающее яйцо")
canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, bg="white")
canvas.pack()
egg_x = WIDTH // 2
egg_y = HEIGHT // 2
def draw_egg(x, y):
canvas.delete("egg")
canvas.create_oval(x, y, x + PERSON_WIDTH, y + PERSON_HEIGHT, fill="lightyellow", outline="black", width=2, tags="egg")
def move_egg(event):
global egg_x, egg_y
distance_x = event.x - (egg_x + PERSON_WIDTH // 2)
distance_y = event.y - (egg_y + PERSON_HEIGHT // 2)
if distance_x != 0:
speed_x = -BASE_SPEED * (distance_x / abs(distance_x)) * 2
else:
speed_x = 0
if distance_y != 0:
speed_y = -BASE_SPEED * (distance_y / abs(distance_y)) * 2
else:
speed_y = 0
egg_x = max(0, min(WIDTH - PERSON_WIDTH, egg_x + int(speed_x)))
egg_y = max(0, min(HEIGHT - PERSON_HEIGHT, egg_y + int(speed_y)))
draw_egg(egg_x, egg_y)
draw_egg(egg_x, egg_y)
canvas.bind("<Motion>", move_egg)
root.mainloop()
Результат в ролике: https://vt.tiktok.com/ZSjKQyw5w/
👏4🤯2❤1👍1🎄1
🌐 Генератор (парсинг) мемов на python
Исходный код:
Ссылка на ролик: https://vt.tiktok.com/ZSjo4PVo4/
Исходный код:
import requests
from bs4 import BeautifulSoup
import random
import webbrowser
import os
def fetch_russian_memes(limit=10):
url = "https://pikabu.ru/tag/Мемы"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
response = requests.get(url, headers=headers)
if response.status_code != 200:
print(f"Ошибка: не удалось загрузить страницу")
return []
soup = BeautifulSoup(response.text, "html.parser")
memes = []
for div in soup.find_all("div", class_="story__content"):
img_tag = div.find("img")
if img_tag:
img_url = img_tag.get("src")
if img_url and img_url.startswith("https://"):
memes.append(img_url)
return memes[:limit]
def create_html(meme_url):
html_content = f"""
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Meme</title>
<style>
body {{
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
background-color: black;
}}
img {{
max-width: 100%;
max-height: 100%;
border: none;
}}
</style>
</head>
<body>
<img src="{meme_url}" alt="Meme">
</body>
</html>
"""
file_name = "random_meme.html"
with open(file_name, "w", encoding="utf-8") as file:
file.write(html_content)
return file_name
def get_previous_memes():
if os.path.exists("мемы.txt"):
with open("мемы.txt", "r", encoding="utf-8") as file:
used_memes = set(file.read().splitlines())
else:
used_memes = set()
return used_memes
def save_used_meme(meme_url):
with open("мемы.txt", "a", encoding="utf-8") as file:
file.write(meme_url + "\n")
if name == "main":
print("Загрузка мема...")
memes_list = fetch_russian_memes(limit=10)
if not memes_list:
print("Не удалось найти мемы")
else:
used_memes = get_previous_memes()
new_memes = [meme for meme in memes_list if meme not in used_memes]
if not new_memes:
print("Все мемы уже показаны :/")
else:
meme_url = random.choice(new_memes)
print(f"Ссылка на мем: {meme_url}")
html_file = create_html(meme_url)
webbrowser.open(f"file://{os.path.abspath(html_file)}")
save_used_meme(meme_url)
Ссылка на ролик: https://vt.tiktok.com/ZSjo4PVo4/
👍5🎄1