如何先在后台运行Python程序进程,然后在前台以EXE文件的形式自动运行一段时间?

2024-06-02 06:01:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python程序,它有两个部分,应该作为.exe文件运行(我可以转换),其目的是在一定时间后(例如60分钟)提醒pc用户休息时间。 单击.exe文件后,第一部分应在后台运行一段时间,时间到了,Tkinter窗口(第二部分)应在前台自动显示给用户。 实际上,它在PyCharm中确实可以工作(仅作为代码),但是如果我将代码转换为.exe格式或.pyw文件,它就不能正常工作(只是什么都不做)

这是我的代码(我是初学者,所以可能有点长)

import time
from tkinter import *
from tkinter import messagebox
import tkinter as tk



root = Tk()



def exit_code():
    messagebox.showinfo("Reminder", "Do Not Forget To Take A Break..!")
    root.quit()



def lockWindow():
    import ctypes
    ctypes.windll.user32.LockWorkStation()
    root.quit()




def Timer():
    BreakTime = "5-10 mins"
    timer = 0
    while timer < 10:   # Until the veriable "timer" reaches the certain amount, the all process should be in background
        timer+=1
        time.sleep(1)
        if timer==10:    # Then after the "timer" reaches the amount, the rest of the program should run in foreground
            root.title('Screen Time')
            root.geometry('430x180')
            root.config(bg='#000039')

            # Tkinter Section
            Txt = Text(root, height=4, width=25)
            timer = f"""ScreenTime; <{timer} mins>\n\nIt's {BreakTime} Break Time"""
            b1 = Button(root, text="Exit", command=exit_code, padx=20, pady=1)
            b1.pack(expand=True, side=LEFT and BOTTOM)
            b2 = Button(root, text="Lock Screen", command=lockWindow, padx=15, pady=1)
            b2.pack(expand=True, side=RIGHT and BOTTOM)


            Txt.pack()
            b1.pack()
            b2.pack()
            Txt.insert(tk.END, timer)
            break
        else:
            continue


Timer()
root.mainloop()

首先,我需要解决上述问题,如果可能的话,我还想添加“推迟”功能,但我做不到。。! 例如,如果用户按下“推迟”按钮,进程应再次移动到后台,并且在延迟一段时间后,Tkinder窗口应再次显示,依此类推。。!这可能吗? 提前感谢;)