使代码行在特定时间运行python3

2024-04-25 22:31:37 发布

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

我正在用Python为我的老师编写一个代码,我需要帮助使代码在指定的时间运行。现在,我只是想让代码在实现程序的简单功能之前运行。。。你知道吗

我希望代码在每次上课时运行。我做不到。下面是基本代码。你知道吗

import datetime
from datetime import date
import calendar

while True:
    my_date = date.today()
    day=calendar.day_name[my_date.weekday()]
    time_now = datetime.datetime.now()

    if day == 'Monday':
        if time_now.hour >= 9 and time_now.minute >= 10:
            if time_now.hour >= 10 and time_now.minute >= 30:
                if time_now.hour >= 11 and time_now.minute >= 30:
                    if time_now.hour >= 13 and time_now.minute >= 10:
                        if time_now.hour >= 14 and time_now.minute >= 5:
                            #period 5
                        else:
                            #period 4
                    else:
                        #period 3
                else:
                    #period 2
            else:
                #period 1

        else:
            continue
            #not in range

下面是我目前的代码,我很满意-相反,我想用一个自动类选择器替换下拉菜单。我建议你运行这个,这样你就能明白我的意思。你知道吗

import tkinter as tk                # python 3
from tkinter import font  as tkfont # python 3
import math
from tkinter import StringVar
from tkinter import *
import random

#import Tkinter as tk     # python 2
#import tkFont as tkfont  # python 2
radius=0
radiususe=0


class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage, PageOne, PageTwo, PageThree, PageFour, PageFive, PageSix, PageSeven):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            # put all of the pages in the same location;
            # the one on the top of the stacking order
            # will be the one that is visible.
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()


class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        tkvar = StringVar(self)

        # Dictionary with options
        choices = [
        'Year 7',
        'Year 8',
        'Year 9',
        'Year 10 Computer Science',
        'Year 10 Geography',
        'Year 11 Computer Science',
        'Year 11 Geography'
        ]
        tkvar.set('Please select class')

        popupMenu = OptionMenu(self, tkvar, *choices)
        popupMenu.pack(fill="none", expand=True)

        # on change dropdown value
        def change_dropdown(*args):
            tkvar.get()
            actionselected=tkvar.get()
            if actionselected == "Year 7":
                controller.show_frame("PageOne")
            elif actionselected == "Year 8":
                controller.show_frame("PageThree")
            elif actionselected == "Year 9":
                controller.show_frame("PageTwo")
            elif actionselected == "Year 10 Computer Science":
                controller.show_frame("PageFour")
            elif actionselected == "Year 10 Geography":
                controller.show_frame("PageFive")
            elif actionselected == "Year 11 Computer Science":
                controller.show_frame("PageSix")
            elif actionselected == "Year 11 Geography":
                controller.show_frame("PageSeven")


        # link function to change dropdown
        tkvar.trace('w', change_dropdown)


class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        year7list=['name1','name2','name3']

        def year7():
            global year7list
            year7backup=['name1','name2','name3']
            try:
                elem = random.choice(year7list)
                name_output.config(text=elem)
                year7list.remove(elem)
            except:
                year7list=year7backup
                elem = random.choice(year7list)
                name_output.config(text=elem)
                year7list.remove(elem)


        text1=tk.Label(self, text="     Current Class: Year 7     \n")
        text1.pack()

        button = tk.Button(self, text="New Name", command=year7)
        button.pack()

        name=tk.Label(self, text="Name: ")
        name.pack()

        name_output = tk.Label(self)
        name_output.pack()

        self.bind('<Return>', year7)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack()


class PageTwo(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        year8list=['name1','name2','name3']

        def year8():
            global year8list
            year8backup=['name1','name2','name3']
            try:
                elem = random.choice(year8list)
                name_output.config(text=elem)
                year8list.remove(elem)
            except:
                year8list=year8backup
                elem = random.choice(year8list)
                name_output.config(text=elem)
                year8list.remove(elem)


        text1=tk.Label(self, text="     Current Class: Year 8     \n")
        text1.pack()

        button = tk.Button(self, text="New Name", command=year8)
        button.pack()

        name=tk.Label(self, text="Name: ")
        name.pack()

        name_output = tk.Label(self)
        name_output.pack()

        self.bind('<Return>', year8)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack()

class PageThree(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        year9list=['name1','name2','name3']

        def year9():
            global year9list
            year9backup=['name1','name2','name3']
            try:
                elem = random.choice(year9list)
                name_output.config(text=elem)
                year9list.remove(elem)
            except:
                year9list=year9backup
                elem = random.choice(year9list)
                name_output.config(text=elem)
                year9list.remove(elem)


        text1=tk.Label(self, text="     Current Class: Year 9     \n")
        text1.pack()

        button = tk.Button(self, text="New Name", command=year9)
        button.pack()

        name=tk.Label(self, text="Name: ")
        name.pack()

        name_output = tk.Label(self)
        name_output.pack()

        self.bind('<Return>', year9)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack()

class PageFour(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        year10cslist=['Sean','Jordan','Naaman', 'Chacrid', 'Gabby', 'Charlie', 'Martin', 'Kaleb', 'Lara','Shaelyn','Megan','Jack','Josh','Ollie','Melissa','Eva','Poppy']

        def year10cs():
            global year10cslist
            year10csbackup=['Sean','Jordan','Naaman', 'Chacrid', 'Gabby', 'Charlie', 'Martin', 'Kaleb', 'Lara','Shaelyn','Megan','Jack','Josh','Ollie','Melissa','Eva','Poppy']
            try:
                elem = random.choice(year10cslist)
                name_output.config(text=elem)
                year10cslist.remove(elem)
            except:
                year10cslist=year10csbackup
                elem = random.choice(year10cslist)
                name_output.config(text=elem)
                year10cslist.remove(elem)


        text1=tk.Label(self, text="     Current Class: Year 10 Computer Science     \n")
        text1.pack()

        button = tk.Button(self, text="New Name", command=year10cs)
        button.pack()

        name=tk.Label(self, text="Name: ")
        name.pack()

        name_output = tk.Label(self)
        name_output.pack()

        self.bind('<Return>', year10cs)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack()


class PageFive(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        year10geolist=['Mark','Martin','Kaleb','Shaelyn','Jack','Josh','Ollie','Malindi','Eva']

        def year10geo():
            global year10geolist
            year10geobackup=['Mark','Martin','Kaleb','Shaelyn','Jack','Josh','Ollie','Malindi','Eva']
            try:
                elem = random.choice(year10geolist)
                name_output.config(text=elem)
                year10geolist.remove(elem)
            except:
                year10geolist=year10geobackup
                elem = random.choice(year10geolist)
                name_output.config(text=elem)
                year10geolist.remove(elem)


        text1=tk.Label(self, text="     Current Class: Year 10 Geography     \n")
        text1.pack()

        button = tk.Button(self, text="New Name", command=year10geo)
        button.pack()

        name=tk.Label(self, text="Name: ")
        name.pack()

        name_output = tk.Label(self)
        name_output.pack()

        self.bind('<Return>', year10geo)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack()

class PageSix(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        year11cslist=['name1','name2','name3']

        def year11cs():
            global year11cslist
            year11csbackup=['name1','name2','name3']
            try:
                elem = random.choice(year11cslist)
                name_output.config(text=elem)
                year11cslist.remove(elem)
            except:
                year11cslist=year11csbackup
                elem = random.choice(year11cslist)
                name_output.config(text=elem)
                year11cslist.remove(elem)


        text1=tk.Label(self, text="     Current Class: Year 11 Computer Science     \n")
        text1.pack()

        button = tk.Button(self, text="New Name", command=year11cs)
        button.pack()

        name=tk.Label(self, text="Name: ")
        name.pack()

        name_output = tk.Label(self)
        name_output.pack()

        self.bind('<Return>', year11cs)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))


class PageSeven(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        year11geolist=['name1','name2','name3']

        def year11geo():
            global year11geolist
            year11geobackup=['name1','name2','name3']
            try:
                elem = random.choice(year11geolist)
                name_output.config(text=elem)
                year11geolist.remove(elem)
            except:
                year11geolist=year11geobackup
                elem = random.choice(year11geolist)
                name_output.config(text=elem)
                year11geolist.remove(elem)


        text1=tk.Label(self, text="     Current Class: Year 11 Geography     \n")
        text1.pack()

        button = tk.Button(self, text="New Name", command=year11geo)
        button.pack()

        name=tk.Label(self, text="Name: ")
        name.pack()

        name_output = tk.Label(self)
        name_output.pack()

        self.bind('<Return>', year11geo)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack()


if __name__ == "__main__":
    app = SampleApp()
    app.title("Name Generator --- V1.0")
    app.mainloop()

谢谢你的帮助, 肖恩


Tags: thetextnameselfoutputinitdefbutton
2条回答

我已经用这个代码解决了这个问题:

import tkinter as tk                # python 3
from tkinter import font  as tkfont # python 3
from tkinter import StringVar
from tkinter import *
import datetime
from datetime import datetime, time
import calendar
import random
import datetime
from datetime import date
from datetime import *
from datetime import datetime


def getclass():
    my_date = date.today()
    day=calendar.day_name[my_date.weekday()]
    now = datetime.now()
    time_now = now.time()

    def selecttimemonday():
        if time(9,10) <= now.time() <= time(10,10):
            print("Period 1 Monday")
        elif time(10,30) <=now.time() < time(11,30):
            print("Period 2 Monday")
            year10cs()
        elif time(11,30) <=now.time() < time(12,30):
            print("Period 3 Monday")
        elif time(13,10) <=now.time() < time(14,5):
            print("Period 4 Monday")
        elif time(14,5) <=now.time() < time(15,1):
            print("Period 5 Monday")
        else:
            print("Not during class time")

    def selecttimetuesday():
        if time(8,35) <= now.time() <= time(9,40):
            print("Period 1 Tuesday")
        elif time(10,20) <=now.time() < time(11,20):
            print("Period 2 Tuesday")
        elif time(11,20) <=now.time() < time(12,20):
             print("Period 3 Tuesday")
        elif time(13,10) <=now.time() < time(14,5):
            print("Period 4 Tuesday")
        elif time(14,5) <=now.time() < time(15,1):
            print("Period 5 Tuesday")
        else:
            print("Not during class time")

    def selecttimewednesday():
        if time(8,35) <= now.time() <= time(9,40):
            print("Period 1 Wednesday")
        elif time(10,20) <=now.time() < time(11,20):
            print("Period 2 Wednesday")
            year10cs()
        elif time(11,20) <=now.time() < time(12,20):
            print("Period 3 Wednesday")
        elif time(13,10) <=now.time() < time(14,5):
            print("Period 4 Wednesday")
        elif time(14,5) <=now.time() < time(15,1):
            print("Period 5 Wednesday")
        else:
            print("Not during class time")

    def selecttimethursday():
        if time(8,35) <= now.time() <= time(9,40):
            print("Period 1 Thursday")
            year10cs()
        elif time(10,20) <=now.time() < time(11,20):
            print("Period 2 Thursday")
        elif time(11,20) <=now.time() < time(12,20):
            print("Period 3 Thursday")
        elif time(13,10) <=now.time() < time(14,5):
            print("Period 4 Thursday")
        elif time(14,5) <=now.time() < time(15,1):
            print("Period 5 Thursday")
        else:
            print("Not during class time")

    def selecttimefriday():
        if time(8,35) <= now.time() <= time(9,40):
            print("Period 1 Friday")
        elif time(10,20) <=now.time() < time(11,20):
            print("Period 2 Friday")
        elif time(11,20) <=now.time() < time(12,20):
            print("Period 3 Friday")
        elif time(13,10) <=now.time() < time(14,5):
            print("Period 4 Friday")
        elif time(14,5) <=now.time() < time(15,1):
            print("Period 5 Friday")
        else:
            print("Not during class time")

    if day == "Monday":
        selecttimemonday()
    elif day == "Tuesday":
        selecttimetuesday()
    elif day == "Wednesday":
        selecttimewednesday()
    elif day == "Thursday":
        selecttimethursday()
    elif day == "Friday":
        selecttimefriday()
    else:
        ("Not weekday")

谢谢你的帮助!你知道吗

import datetime
import time
from datetime import date
import calendar
#definene your schedule in the dict
trigger_times = {
                 'Monday':'9:10,10:30,12:30',
                 'Tuesday':'9:10,10:30,12:30',
                 'Wednesday':'9:10,10:30,12:30',
                 'Thursday':'9:10,10:30,12:30',
                 'Friday':'9:10,10:30,12:30',
                 'Saturday':'9:10,10:30,12:30',
                 'Sunday':'9:10,10:30,12:30'}

triggered=False
while True:
    my_date = date.today()
    day=calendar.day_name[my_date.weekday()]
    time_now = datetime.datetime.now()
    task_for_today = trigger_times[day]#selects the schedule for today

    #this returns list of the values with key current day
    #you have trigger_items which is a dict 
    # day = *Monday*, then we pick the values from the key *Monday* 
    # hours to trigger = '9:10,10:30,12:30'
    # next we split them and then we look if time_now is in there to execute the function

    #these are the hours that the code is suppose to be executed
    hours_to_trigger = task_for_today.split(',')

    #time_now is the current time 10:30
    time_now = str(time_now.strftime("%H:%M"))


    #here checks if time_now in hours_to_trigger
    # if '10:30' in ['9:10', '10:30', '12:30']
    # if true will run the task 
    #triggered is the var that says if the task has been triggered you dont want it to loop for 60secs
    if time_now in hours_to_trigger and triggered ==False:
            print("Task is triggered in",time_now)
            #here you put the trigger to the function you want to trigger
            triggered == True
    else:
        triggered = False

相关问题 更多 >