while y_house < HEIGHT:
y += 9.8
Вы меняете y
, но y
у вас никак не связано с y_house
, из-за чего этот цикл получается бесконечным (y_house
не меняется и так и остается меньше HEIGHT
).while y_house < HEIGHT:
y_house += 9.8
from aiogram import Bot, Dispatcher, types
from aiogram.types import ChatPermissions
API_TOKEN = 'YOUR_BOT_API_TOKEN'
bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot)
@dp.message_handler(commands=['start'])
async def start(message: types.Message):
chat_member = await bot.get_chat_member(chat_id=message.chat.id, user_id=bot.id)
if chat_member.status not in ['administrator', 'creator']:
await message.reply("Бот должен быть администратором группы.")
return
await bot.promote_chat_member(
chat_id=message.chat.id,
user_id=bot.id,
is_anonymous=True,
can_manage_chat=True,
can_delete_messages=True,
can_manage_video_chats=True,
can_restrict_members=True,
can_promote_members=True,
can_change_info=True,
can_invite_users=True,
can_pin_messages=True
)
await message.reply("Бот теперь администратор и может отправлять сообщения от имени группы.")
if __name__ == '__main__':
from aiogram import executor
executor.start_polling(dp, skip_updates=True)
import time
import multiprocessing
from threading import Thread
from tkinter import *
from tkinter import ttk
# Функция контроля работы потока расчета
def monitor_process(calc_process, window):
while calc_process.is_alive():
print("Process is running")
time.sleep(0.2)
else:
window.destroy()
# Функция выполнения расчета
def perform_calculation(multiplier):
i = 0
while i < 10**6:
i += 1
result = i * multiplier
print(result)
# Функция открытия окна при расчете
def start_calculation(output_label):
# Функция закрытия окна по нажатию кнопки
def stop_calculation():
calc_process.terminate()
window.destroy() # Закрытие окна
# Новое вспомогательное окно
window = Toplevel()
window.geometry(
f"{int(main_window_width / 2)}x{int(main_window_height / 2)}+{int(
screen_width + main_window_width / 4)}+{int(screen_height + main_window_height / 4)}"
)
stop_button = Button(
master=window,
text="Stop",
cursor="hand2",
border=4,
command=stop_calculation,
activebackground="white",
activeforeground="black",
bd=5,
font=("Times", "12"),
)
stop_button.pack(anchor="sw", pady=5, padx=0)
calc_process = multiprocessing.Process(
target=perform_calculation, args=(2,), daemon=True
) # Поток расчета
monitor_thread = Thread(
target=monitor_process, args=(calc_process, window), daemon=True
) # Поток контроля
calc_process.start() # Запуск потока расчета
monitor_thread.start() # Запуск потока контроля
window.mainloop()
if __name__ == "__main__":
root = Tk()
# Размер и положение окна
main_window_width = 500
main_window_height = 500
# Определение разрешения экрана по ширине
screen_width = root.winfo_screenwidth()
# Определение разрешения экрана по высоте
screen_height = root.winfo_screenheight()
# Определение координат середины экрана по ширине
screen_width = screen_width // 2 - main_window_width // 2
# Определение координат середины экрана по высоте
screen_height = screen_height // 2 - main_window_height // 2
root.geometry(
f"{main_window_width}x{main_window_height}+{int(screen_width)
}+{int(screen_height)}"
) # Размер и положение окна
# Надписи
label_res = Label(master=root, text="Запуск расчета")
output_label = Label(master=root, text="")
# Кнопка запуска расчета
start_button = Button(
master=root,
text="ПУСК!",
cursor="hand2",
border=4,
command=lambda: start_calculation(output_label),
activebackground="white",
activeforeground="black",
bd=5,
font=("Times", "12"),
)
# Размещение виджетов
label_res.pack(pady=5)
start_button.pack(anchor="center", pady=50, padx=0)
root.mainloop()
pip install pyinstaller
try:
os.chdir(sys._MEIPASS)
except AttributeError:
pass
Ну напримерimport os
import sys
# some code
if __name__ == "__main__":
try:
os.chdir(sys._MEIPASS)
except AttributeError:
pass
images
images
. Например, если вы храните фото в project/images
зайдите в project
pyinstaller main.py -F -w -n "Name_of_project" --add-data "images/*;images"
dist
будет лежать exe. Запускаем и проверяемimport mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="database_name",
connection_timeout=86400, # таймаут подключения в секундах (86400 секунд = 24 часа)
)
pool_ping_interval=300
datetime.time(hour=12, minute=50, second=0)
, то на самом деле это будет 15:50 по МСК. Т. е. для решения этой проблемы, я думаю, нужно или вычитать из времени сколько-то часов (в данном случае 3) или конвертировать местное время в UTC:from datetime import datetime
import pytz
local = pytz.timezone("Europe/Moscow")
naive = datetime.strptime("2024-12-4 12:50:00", "%Y-%m-%d %H:%M:%S")
local_dt = local.localize(naive, is_dst=None)
utc_dt = local_dt.astimezone(pytz.utc)
aiogram==2.25.1
Как мне такое реализовать, с учетом того, что я <...> в асинхроне ничего не понимаю?
finally:
if connection: # Завершение работы базы данных
connection.close()
print("Завершение работы базы данных")
замените на это else:
if connection: # Завершение работы базы данных
connection.close()
print("Завершение работы базы данных")
finally
выполняется в любом случае, а else
только если не возникло исключения.