#Рисованиеtkinter
Код из видео:
from tkinter import *
root = Tk()
root.title('Рисование')
root.geometry('800x600')
root.resizable(width=False, height=False)
canvas = Canvas(root, bg='white', width=800, height=600)
canvas.create_rectangle(150, 150, 250, 250, fill='lime', width=10, outline='brown')
canvas.create_line(300, 300, 450, 450, width=5, fill='yellow')
canvas.create_oval(400, 200, 600, 400, fill='green', outline='brown', width=5)
canvas.create_polygon(100, 100, 200, 100, 200, 200, 100, 200, 100, 100)
canvas.pack()
root.mainloop()
Код из видео:
from tkinter import *
root = Tk()
root.title('Рисование')
root.geometry('800x600')
root.resizable(width=False, height=False)
canvas = Canvas(root, bg='white', width=800, height=600)
canvas.create_rectangle(150, 150, 250, 250, fill='lime', width=10, outline='brown')
canvas.create_line(300, 300, 450, 450, width=5, fill='yellow')
canvas.create_oval(400, 200, 600, 400, fill='green', outline='brown', width=5)
canvas.create_polygon(100, 100, 200, 100, 200, 200, 100, 200, 100, 100)
canvas.pack()
root.mainloop()
#ПростоеПриложениеTkinter
Код из видео:
from tkinter import *
from random import choice
def click():
color = choice(colors)
root['bg'] = color
btn['text'] = color
btn['fg'] = color
root = Tk()
root.title('Цветная кнопка')
root.geometry('200x200')
root.resizable(width=False, height=False)
root['bg'] = 'white'
colors = ['white', 'black', 'lime', 'brown', 'yellow', 'red', 'blue']
btn = Button(root, text='Нажми на меня', fg='lime', bg='grey', width='13', font='Arial 15 bold', command=click)
btn.pack(expand=1, anchor=CENTER)
root.mainloop()
Код из видео:
from tkinter import *
from random import choice
def click():
color = choice(colors)
root['bg'] = color
btn['text'] = color
btn['fg'] = color
root = Tk()
root.title('Цветная кнопка')
root.geometry('200x200')
root.resizable(width=False, height=False)
root['bg'] = 'white'
colors = ['white', 'black', 'lime', 'brown', 'yellow', 'red', 'blue']
btn = Button(root, text='Нажми на меня', fg='lime', bg='grey', width='13', font='Arial 15 bold', command=click)
btn.pack(expand=1, anchor=CENTER)
root.mainloop()
#ПарсерФото
Код из видео:
from icrawler.builtin import GoogleImageCrawler
google_crawler = GoogleImageCrawler(storage={'root_dir': 'C:/Users/lfybk/OneDrive/Рабочий стол/Lessons/парсер/Download'})
print('Сколько нужно спарсить фото?')
quabtity = int(input())
print('По какому запросу парсить фото?')
name = str(input())
google_crawler.crawl(keyword=name, max_num=quabtity)
Код из видео:
from icrawler.builtin import GoogleImageCrawler
google_crawler = GoogleImageCrawler(storage={'root_dir': 'C:/Users/lfybk/OneDrive/Рабочий стол/Lessons/парсер/Download'})
print('Сколько нужно спарсить фото?')
quabtity = int(input())
print('По какому запросу парсить фото?')
name = str(input())
google_crawler.crawl(keyword=name, max_num=quabtity)
#pygameУправлениеКлавиатурой
Код из видео:
import pygame
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
WIDTH = 800
HEIGHT = 650
class Player(pygame.sprite.Sprite):
def init(self):
pygame.sprite.Sprite.init(self)
self.image = pygame.Surface((50, 50))
self.image.fill(RED)
self.rect = self.image.get_rect()
self.rect.center = (WIDTH / 2, HEIGHT / 2)
def update(self):
if self.rect.left > WIDTH:
self.rect.left = 0
if self.rect.right < 0:
self.rect.left = WIDTH
if self.rect.top > HEIGHT:
self.rect.bottom = 0
if self.rect.bottom < 0:
self.rect.top = HEIGHT
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.rect.x -= 5
if keys[pygame.K_RIGHT]:
self.rect.x += 5
if keys[pygame.K_UP]:
self.rect.y -= 5
if keys[pygame.K_DOWN]:
self.rect.y += 5
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Тестовый заголовок')
all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
running = True
while running:
pygame.time.delay(10)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
all_sprites.update()
screen.fill(YELLOW)
all_sprites.draw(screen)
pygame.display.flip()
pygame.quit()
Код из видео:
import pygame
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
WIDTH = 800
HEIGHT = 650
class Player(pygame.sprite.Sprite):
def init(self):
pygame.sprite.Sprite.init(self)
self.image = pygame.Surface((50, 50))
self.image.fill(RED)
self.rect = self.image.get_rect()
self.rect.center = (WIDTH / 2, HEIGHT / 2)
def update(self):
if self.rect.left > WIDTH:
self.rect.left = 0
if self.rect.right < 0:
self.rect.left = WIDTH
if self.rect.top > HEIGHT:
self.rect.bottom = 0
if self.rect.bottom < 0:
self.rect.top = HEIGHT
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.rect.x -= 5
if keys[pygame.K_RIGHT]:
self.rect.x += 5
if keys[pygame.K_UP]:
self.rect.y -= 5
if keys[pygame.K_DOWN]:
self.rect.y += 5
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Тестовый заголовок')
all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
running = True
while running:
pygame.time.delay(10)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
all_sprites.update()
screen.fill(YELLOW)
all_sprites.draw(screen)
pygame.display.flip()
pygame.quit()
#ГенераторТекста
Код из видео:
import numpy as np
text = open('text.txt', encoding='utf-8').read()
corpus = text.split()
def make_pairs(corpus):
for i in range(len(corpus) - 1):
yield (corpus[i], corpus[i + 1])
pairs = make_pairs(corpus)
word_dict = {}
for word_1, word_2 in pairs:
if word_1 in word_dict.keys():
word_dict[word_1].append(word_2)
else:
word_dict[word_1] = [word_2]
first_word = np.random.choice(corpus)
while first_word.islower():
first_word = np.random.choice(corpus)
chain = [first_word]
n_words = 100
for i in range(n_words):
chain.append(np.random.choice(word_dict[chain[-1]]))
print(' '.join(chain))
Код из видео:
import numpy as np
text = open('text.txt', encoding='utf-8').read()
corpus = text.split()
def make_pairs(corpus):
for i in range(len(corpus) - 1):
yield (corpus[i], corpus[i + 1])
pairs = make_pairs(corpus)
word_dict = {}
for word_1, word_2 in pairs:
if word_1 in word_dict.keys():
word_dict[word_1].append(word_2)
else:
word_dict[word_1] = [word_2]
first_word = np.random.choice(corpus)
while first_word.islower():
first_word = np.random.choice(corpus)
chain = [first_word]
n_words = 100
for i in range(n_words):
chain.append(np.random.choice(word_dict[chain[-1]]))
print(' '.join(chain))
👍2
#ПостроениеГрафиков
Код из видео:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
ax.set_title('График')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_xlim((-5, 5))
ax.set_ylim((-5, 5))
ax.grid()
x = np.linspace(-5, 5, 100)
y = x2 + np.cos(x) - x3
ax.plot(x, y)
plt.show()
Код из видео:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
ax.set_title('График')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_xlim((-5, 5))
ax.set_ylim((-5, 5))
ax.grid()
x = np.linspace(-5, 5, 100)
y = x2 + np.cos(x) - x3
ax.plot(x, y)
plt.show()
#ПарсерСайтов
Код из видео:
from bs4 import BeautifulSoup
from urllib.request import urlopen
url = [
""
]
file = open('text.txt', 'a')
for x in url:
html_code = str(urlopen(x).read(), 'utf-8')
soup = BeautifulSoup(html_code, 'html.parser')
s = soup.find('title').text
file.write(s + '\n')
p = soup.find_all('p')
print(s)
for i in p:
print(i.text)
file.write(i.text + '\n')
file.write('\n\n')
file.close()
Код из видео:
from bs4 import BeautifulSoup
from urllib.request import urlopen
url = [
""
]
file = open('text.txt', 'a')
for x in url:
html_code = str(urlopen(x).read(), 'utf-8')
soup = BeautifulSoup(html_code, 'html.parser')
s = soup.find('title').text
file.write(s + '\n')
p = soup.find_all('p')
print(s)
for i in p:
print(i.text)
file.write(i.text + '\n')
file.write('\n\n')
file.close()
🔥1
#ПрограммаПредсказатель
Код из видео:
import random
import time
responses = ['Да', 'Нет', 'Возможно', 'Скорее да, чем нет', 'Скорее нет, чем да']
def answer():
input('Задай мне вопрос: ')
print('Хмм...')
time.sleep(2)
print(random.choice(responses))
print('\n')
answer()
anotherQuestion = input('Хотите задать ещё 1 вопрос? д/н: ')
while anotherQuestion == str('д'):
answer()
anotherQuestion = input('Хотите задать ещё 1 вопрос? д/н: ')
else:
print(input('Нажмите на любую клавишу для выхода'))
Код из видео:
import random
import time
responses = ['Да', 'Нет', 'Возможно', 'Скорее да, чем нет', 'Скорее нет, чем да']
def answer():
input('Задай мне вопрос: ')
print('Хмм...')
time.sleep(2)
print(random.choice(responses))
print('\n')
answer()
anotherQuestion = input('Хотите задать ещё 1 вопрос? д/н: ')
while anotherQuestion == str('д'):
answer()
anotherQuestion = input('Хотите задать ещё 1 вопрос? д/н: ')
else:
print(input('Нажмите на любую клавишу для выхода'))
👍1
#БудильникНаПитоне
Код из видео:
from playsound import *
from datetime import *
def validate_time(alarm_time):
if len(alarm_time) != 8:
return 'Неверный формат, попробуйте ещё раз.'
else:
if int(alarm_time[0:2]) > 23:
return 'Неверный формат часов, попробуйте ещё раз.'
elif int(alarm_time[3:5]) > 59:
return 'Неверный формат минут, попробуйте ещё раз.'
elif int(alarm_time[6:8]) > 59:
return 'Неверный формат секунд, попробуйте ещё раз.'
else:
return 'Отлично!'
while True:
alarm_time = input('Введите время в следующем формате \'HH:MM:SS\' \nВремя будильника: ')
validate = validate_time(alarm_time)
if validate != 'Отлично!':
print(validate)
else:
print(f"Будильник установлен на время {alarm_time}...")
break
alarm_hour = int(alarm_time[0:2])
alarm_min = int(alarm_time[3:5])
alarm_sec = int(alarm_time[6:8])
while True:
now = datetime.now()
current_hour = now.hour
current_min = now.minute
current_sec = now.second
if alarm_hour == current_hour:
if alarm_min == current_min:
if alarm_sec == current_sec:
print('Вставай!')
playsound('C:/1.mp3')
break
Код из видео:
from playsound import *
from datetime import *
def validate_time(alarm_time):
if len(alarm_time) != 8:
return 'Неверный формат, попробуйте ещё раз.'
else:
if int(alarm_time[0:2]) > 23:
return 'Неверный формат часов, попробуйте ещё раз.'
elif int(alarm_time[3:5]) > 59:
return 'Неверный формат минут, попробуйте ещё раз.'
elif int(alarm_time[6:8]) > 59:
return 'Неверный формат секунд, попробуйте ещё раз.'
else:
return 'Отлично!'
while True:
alarm_time = input('Введите время в следующем формате \'HH:MM:SS\' \nВремя будильника: ')
validate = validate_time(alarm_time)
if validate != 'Отлично!':
print(validate)
else:
print(f"Будильник установлен на время {alarm_time}...")
break
alarm_hour = int(alarm_time[0:2])
alarm_min = int(alarm_time[3:5])
alarm_sec = int(alarm_time[6:8])
while True:
now = datetime.now()
current_hour = now.hour
current_min = now.minute
current_sec = now.second
if alarm_hour == current_hour:
if alarm_min == current_min:
if alarm_sec == current_sec:
print('Вставай!')
playsound('C:/1.mp3')
break