微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

运行while循环时如何防止tkinter程序不响应

如何解决运行while循环时如何防止tkinter程序不响应

我已经在tkinter中创建了药物提醒。它可以工作,但是当我单击“通知”按钮时,我的程序死机并说没有响应,但是程序仍然可以工作。

from tkinter import *
from plyer import notification
from datetime import datetime
import tkinter.messageBox as msg

root = Tk()
root.title("Medicine reminder")


def notify():
    msg.showinfo("Reminder Set",f"You will be notified at {timeSlider.get()}. Make sure that you don't close the program")
    while True:
        hour = datetime.Now().hour
        if hour == timeSlider.get():
            notification.notify(
                title=f"Take your medicine {medicine.get()}",message=f"You have scheduled it for {timeSlider.get()}",# displaying time
                timeout=15)
            break


Label(text="Medicine Reminder",font="comicsans 20 bold").pack(anchor="w",padx=10,pady=10)
medicine = StringVar()
medicine_entry = Entry(font="comicsans 20",textvariable=medicine)
medicine_entry.insert(0,"Name of medicine")
medicine_entry.pack(anchor="w",pady=5)
timeSlider = Scale(from_=0,to=24,orient=HORIZONTAL)
Label(text="Enter the time you want to get notified at:",font="comicsans 15").pack(anchor="w",padx=10)
timeSlider.pack(anchor="w",padx=10)
Button(text="Notify me",font="comicsans 15 bold",relief=SUNKEN,borderwidth=6,command=notify).pack(anchor="w",pady=15,padx=10)

root.mainloop()

解决方法

您的代码的问题是,您对SELECT * FROM ( SELECT *,( ( ( acos( sin(( $LATITUDE * pi() / 180)) * sin(( `latitud_fieldname` * pi() / 180)) + cos(( $LATITUDE * pi() /180 )) * cos(( `latitud_fieldname` * pi() / 180)) * cos((( $LONGITUDE - `longitude_fieldname`) * pi()/180))) ) * 180/pi() ) * 60 * 1.1515 ) as distance FROM `myTable` ) myTable WHERE distance <= $DISTANCE_MILES; 使用了无限循环,该循环与while在同一线程上运行,因此由于窗口正忙于while循环,因此它无法运行窗口,使用tkinter内置的after是解决这个问题的一种方法。

方法1(使用tkinter):

after

def notify(): global hour msg.showinfo("Reminder Set",f"You will be notified at {timeSlider.get()}. Make sure that you don't close the program") hour = datetime.now().hour root.after(timeSlider.get()*3600000,alert) #converting hour to ms def alert(): notification.notify( title=f"Take your medicine {medicine.get()}",message=f"You have scheduled it for {timeSlider.get()}",# displaying time timeout=15) 方法主要接受两个参数:

  • after()-该函数的运行时间
  • ms-给定ms结束后要运行的函数。

代码的其余部分保持不变

方法2(线程):

func

只需更改按钮import threading .... Button(text="Notify me",font="comicsans 15 bold",relief=SUNKEN,borderwidth=6,command=threading.Thread(target=notify).start).pack(anchor="w",的参数,其余代码保持不变。这可以解决问题,但是使用线程处理后,效率仍然低下,因此我建议使用方法1。

希望您的疑虑已清除,如果还有其他错误,请告诉我。

欢呼

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。