【问题标题】:Python timetable pass start and finish time that pressed button relevant to positionPython时间表传递按下与位置相关的按钮的开始和结束时间
【发布时间】:2016-02-15 14:59:06
【问题描述】:

对于我的课程作业,我正在制作一个预订系统,我一直在尝试制作一个显示当前一周课程的页面,当单击该按钮时,它会在单独的页面上显示学生的详细信息。但我没有不知道如何将这段时间传递给我的打开页面子(它编写了一个 txt 文件,该文件将用于 SQL 以获取学生的详细信息)。我目前的做法只是将最大时间传递给子。

from tkinter import *
import datetime


class Application(Frame):
    def __init__(self, master):
        """ Initialize the frame. """
        super(Application, self).__init__(master)  
        self.grid()
        self.timetable_button_gen_weekdays()
        self.timetable_button_gen_weekends()


    def timetable_button_gen_weekdays(self):
        c = datetime.datetime(100,1,1,16,00,00)
        self.Monday_lbl = Label(self, text = "Monday")
        self.Monday_lbl.grid(row = 1, column = 0)
        self.Tuesday_lbl = Label(self, text = "Tuesday")
        self.Tuesday_lbl.grid(row = 2, column = 0)
        self.Wednesday_lbl = Label(self, text = "Wednesday")
        self.Wednesday_lbl.grid(row = 3, column = 0)
        self.Thursday_lbl = Label(self, text = "Thursday")
        self.Thursday_lbl.grid(row = 4, column = 0)
        self.Friday_lbl = Label(self, text = "Friday")
        self.Friday_lbl.grid(row = 5, column = 0)
        for k in range(8):
            b = c + datetime.timedelta(minutes = (30 * k))
            d = b + datetime.timedelta(minutes = (30))
            self.i_time_weekdays_lbl = Label(self, text = b.time().strftime('%H:%M')+" to "+d.time().strftime('%H:%M'))
            self.i_time_weekdays_lbl.grid(row = 0, column = k + 1)
        for i in range(5):
            for a in range(8):
                b = c + datetime.timedelta(minutes = (30 * a))
                d = b + datetime.timedelta(minutes = (30))
                bttn_i_a = Button(self, text = "available",command = lambda: self.OpenPage(b.time().strftime('%H:%M'),d.time().strftime('%H:%M')))
                bttn_i_a.grid(row = i + 1, column = a + 1)
                bttn_i_a.config(height = 2, width = 10)

    def timetable_button_gen_weekends(self):
        c = datetime.datetime(100,1,1,10,00,00)
        self.Saturday_lbl = Label(self, text = "Saturday")
        self.Saturday_lbl.grid(row = 8, column = 0)
        self.Sunday_lbl = Label(self, text = "Sunday")
        self.Sunday_lbl.grid(row = 9, column = 0)
        self.weekend_lbl = Label(self, text = "Weekend")
        self.weekend_lbl.grid(row = 6, column = 1, sticky = W)
        for k in range(10):
            b = c + datetime.timedelta(minutes = (30 * k))
            d = b + datetime.timedelta(minutes = (30))
            self.i_time_weekdays_lbl = Label(self, text = b.time().strftime('%H:%M')+" to "+d.time().strftime('%H:%M'))
            self.i_time_weekdays_lbl.grid(row = 7, column = k + 1)
        for i in range(2):
            for a in range(10):
                b = c + datetime.timedelta(minutes = (30 * a))
                d = b + datetime.timedelta(minutes = (30))
                bttn_i_a = Button(self, text = "available",command = lambda: self.OpenPage(b.time().strftime('%H:%M'),d.time().strftime('%H:%M')))
                bttn_i_a.grid(row = i + 8, column = a + 1)
                bttn_i_a.config(height = 2, width = 10)

    def OpenPage(self,startime,finishtime):
        file = open("PassTimes.txt","w")
        file.write(startime)
        file.write("\n")
        file.write(finishtime)
        print(startime)
        print(finishtime)
        filepath = "PresentStudent.py"

        global_namespace = {"__file__": filepath, "__name__": "__main__"}
        with open(filepath, 'rb') as file:
            exec(compile(file.read(), filepath, 'exec'), global_namespace)


root = Tk()
root.title("test")
root.geometry("2000x2000")
app = Application(root)
root.mainloop()

【问题讨论】:

    标签: python loops object button tkinter


    【解决方案1】:

    欢迎来到SO。

    常规

    恕我直言,运行“PresentStudent.py”的主程序看起来并不那么干净。 它可以工作,但主要例程是为直接调用脚本时构建的,而不是在导入并在其他脚本中使用时构建的。

    你知道python中的modules functionality吗?

    我建议在PresentStudent.py 中创建一个函数来执行您在主程序中所做的事情。给函数参数传递.txt-Filename。

    例如

    def presentStudentCall(inputFile):

    并在您的脚本中使用它,例如:

        #!/usr/bin/python
        # -*- coding: utf-8 -*-
    
        # here we import PresentStudent.py, as we import it __main__ will not run
        import PresentStudent
    
        #[...]
    
        def OpenPage(self, stime, etime):
            #[...]
            # Instead of executing a file we call the function from the module
            PresentStudent.presentStudentCall(file)
    

    如果你想在第二帧中显示数据,你也可以在PresentStudent.py 中声明一个类并像这样使用它:

    def OpenPage(self, stime, etime):
        #[...]
        student=PresentStudent.Student() # assuming to name the class "Student"
        student.presentStudentCall(file)
    

    您的问题本身

    使用 lambda 不一定是最好的方法。对于scope and garbage collecting,您的代码只会将最后生成的“b”和“c”传递给定义。

    你可以做的是计算OpenPage中的发件人项目:

    为了实现这一点,我建议您使用数组来存储开始时间。 喜欢

    c = datetime.datetime(100,1,1,16,00,00)    
    self.weektimes    = ["%s"%(c+datetime.timedelta(minutes=30*k)) for k in range(8)]
    self.weekendtimes = ["%s"%((c+datetime.timedelta(minutes=30*k)) for k in range(10)]
    

    首先您需要将点击事件绑定到小部件(在这种情况下是您的按钮) bttn_i_a.bind("<Button-1>", self.OnPage) 您的 OpenPage 可能如下所示:

    def OpenPage(self, event):
        import time
        # With that, we get the row and column where we clicked in
        grid_info=event.widget.grid_info()
    
        # week or weekend?
        if grid_info["row"] > 5: #may depend on amount of headers
            _timearray=self.weekendtimes
        else:
            _timearray=self.weektimes
    
        # get the column
        col=grid_info["column"]
    
        # get the startTime
        stime=_timearray[col]
    
        # end time is +30 minutes
        etime="%s"%(time.strptime("%s"%stime, "%H:%M")+time.struct_time(tm_min=30))
    
        # now call the handler...
    

    【讨论】:

    • 非常感谢,我正在考虑使用它的网格位置,但我找不到方法,显然我看起来不够努力。还要感谢您提供的所有其他建议,我并不是特别热衷于问我的老师,因为我不想看起来很愚蠢,所以我在这里问了。很抱歉给您带来了麻烦。
    猜你喜欢
    • 1970-01-01
    • 2019-10-28
    • 2012-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-03
    • 1970-01-01
    • 2015-10-20
    相关资源
    最近更新 更多