Да, это возможно и очень просто. Вы можете добавить функцию, которая показывает сообщение после 10 нажатий кнопок. Если вы хотите всплывающее сообщение, вы можете использовать модуль tkinter.messagebox
для отображения всплывающих сообщений.
from tkinter import *
from tkinter.messagebox import *
root = Tk()
show_press = Label(root, text='You pressed the Button 0 times')
show_press.pack()
count = 0
def times_pressed():
global count
count+=1
if count >= 10:
# Code to be executed when "water is low"
showwarning("Water is Low", 'Water is over and it needs to be changed.')
show_press['text'] = 'You pressed the Button {} times'.format(count)
button = Button(root, text='Button', command = times_pressed)
button.pack()
root.mainloop()
Чтобы отправить электронное письмо, вы должны использовать другие библиотеки. Я использую smtplib
.
У меня нет большого опыта в этой библиотеке. Я бы порекомендовал вам посмотреть smtplib
документацию . Но я сделал функцию, которая отправляет электронную почту из учетной записи Gmail. Также, если вы используете мою функцию, я бы предложил вам создать новую учетную запись только для отправки электронной почты.
Вот полный код:
import smtplib
from tkinter import *
def Send_Email(email, password, to, subject, message):
"""Sends email to the respected receiver."""
try:
# Only for gmail account.
with smtplib.SMTP('smtp.gmail.com:587') as server:
server.ehlo() # local host
server.starttls() # Puts the connection to the SMTP server.
# login to the account of the sender
server.login(email, password)
# Format the subject and message together
message = 'Subject: {}\n\n{}'.format(subject, message)
# Sends the email from the logined email to the receiver's email
server.sendmail(email, to, message)
print('Email sent')
except Exception as e:
print("Email failed:",e)
count = 0
def times_pressed():
global count
count+=1
if count >= 10:
# Code to be executed when "water is low"
message = "Water is over and it needs to be changed."
Send_Email(
email='tmpaccount@gmail.com', # Gmail account
password='test@123', # Its password
to='Your email address', # Receiver's email
subject='Water is Low', # Subject of mail
message=message ) # The message you want
show_press['text'] = 'You pressed the Button {} times'.format(count)
root = Tk()
show_press = Label(root, text='You pressed the Button 0 times')
show_press.pack()
button = Button(root, text='Button', command = times_pressed)
button.pack()
root.mainloop()
Еще одна вещь, когда электронное письмо отправляет, графический интерфейс пользователя может зависнуть, пока электронное письмо не будет отправлено. Чтобы решить эту проблему, вам нужно использовать модуль threading
и Thread
функцию Send_Email(...)
.
Чтобы использовать многопоточность, вам нужно импортировать ее from threading import Thread
и запускать функцию Send_Email(...)
в отдельном потоке, например
from threading import Thread
...
def times_pressed():
global count
count+=1
if count >= 10:
# Code to be executed when "water is low"
message = "Water is over and it needs to be changed."
thread = Thread( target = Send_Email, kwargs = {
'email' : 'tmpaccount@gmail.com', # Gmail new account
'password' : 'test@123', # Its password
'to' = 'Your email address', # Receiver's email
'subject' : 'Water is Low', # Subject of mail
'message' : message } # The message you want
)
thread.start()
show_press['text'] = 'You pressed the Button {} times'.format(count)
...