在tkin中读取、操作和显示文本文件

2024-04-26 00:04:00 发布

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

我对python很陌生。我试图用tkinter读取一个文本文件,然后进行操作,最后显示结果。所以基本上有三个步骤。在

以下是我的示例文件,它将以以下格式修复:

DOWN 07.11.2016 08:21:33 - 07.11.2016 08:22:33
UP   07.11.2016 09:41:07 - 09.11.2016 09:20:33
DOWN 09.11.2016 08:26:33 - 09.11.2016 08:35:33
UP   09.11.2016 08:23:33 - 09.11.2016 08:25:33
DOWN 09.11.2016 08:36:33 - 09.11.2016 08:38:33
DOWN 10.11.2016 08:36:33 - 10.11.2016 08:38:33

文件包含有关启动和关闭状态的信息。在

第一步: 打开和读取文件

^{pr2}$

第二步:操纵

在这里,我试着浏览每一行,检查是否停机,那么总停机时间是多少,从这个日期起(示例文件),总停机时间是12分钟

第三步: 我想把这12分钟显示为GUI屏幕上操作后的停机时间。 所以最后我在tinkter屏幕上的输出应该是

Total Downtime is 12 min from 07.11.2016 08:21:33

如何实现第2步和第3步,我在互联网上浏览了许多文章,但没有找到任何真正有助于解决这一问题的文章。 任何帮助都会很好。在


Tags: 文件示例屏幕tkinter状态格式文章时间
1条回答
网友
1楼 · 发布于 2024-04-26 00:04:00
try:
    import Tkinter as Tk
    import tkFileDialog as fileDialog
except ImportError:
    import tkinter as Tk
    fileDialog = Tk.filedialog

import datetime

 # Manipulation
def processText(lines):
    total = 0
    start = None
    for k, line in enumerate(lines):
        direction, date1, time1, _, date2, time2 = line.split()
        if direction != "DOWN": continue
        if start==None: start = date1 + ' ' + time1
        # 1
        D1, M1, Y1 = date1.split('.')
        h1, m1, s1 = time1.split(':')
        # 2
        D2, M2, Y2 = date2.split('.')
        h2, m2, s2 = time2.split(':')
        # Timestamps
        t1 = datetime.datetime(*map(int, [Y1, M1, D1, h1, m1, s1])).timestamp()
        t2 = datetime.datetime(*map(int, [Y2, M2, D2, h2, m2, s2])).timestamp()
        total += (t2-t1)
    return total, start

# Opening and updating
def openFile():
    filename = fileDialog.askopenfilename()

    fileHandle = open(filename, 'r')
    down, start = processText(fileHandle.readlines())
    txt = "Total Downtime is {0} min from {1}".format(down//60, start)
    textVar.set(txt)

    fileHandle.close()

 # Main
root = Tk.Tk()

button = Tk.Button(root, text="Open", command=openFile)
button.grid(column=1, row=1)

textVar = Tk.StringVar(root)
label = Tk.Label(root, textvariable=textVar)
label.grid(column=1, row=2)

root.mainloop()

相关问题 更多 >