Skip to main content
 首页 » 编程设计

python之在 tkinter 中读取、操作和显示文本文件

2024年09月07日26soundcode

我是 python 的新手。我正在尝试使用 tkinter 读取文本文件,然后进行操作,最后显示结果。所以基本上有 3 个步骤。

这是我的示例文件,格式固定为:

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 

文件包含有关 UP 和 DOWN 状态的信息。

第一步: 打开并读取文件

from tkinter import * 
from tkinter import ttk 
from tkinter import filedialog 
interface = Tk() 
def openfile(): 
    return filedialog.askopenfilename() 
button = ttk.Button(interface, text="Open", command=openfile)  # <------ 
button.grid(column=1, row=1) 
 
interface.mainloop() 

第 2 步:操纵

在这里,我试图遍历每一行并检查它是否 DOWN 那么​​总停机时间是多少,在这种情况下(样本文件)总停机时间是 12 分钟。

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

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

我怎样才能实现第 2 步和第 3 步,我在互联网上浏览了很多文章,但找不到任何真正有助于解决这个问题的东西。 任何帮助都会很棒。

请您参考如下方法:

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()