Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 提供用户输入tkinter_Python_Python 3.x_Python 2.7_Tkinter_Tkinter Entry - Fatal编程技术网

Python 提供用户输入tkinter

Python 提供用户输入tkinter,python,python-3.x,python-2.7,tkinter,tkinter-entry,Python,Python 3.x,Python 2.7,Tkinter,Tkinter Entry,我有一个场景,我上传一个文本文件,然后提供一个用户输入,然后根据用户输入进一步处理 示例文件: 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.201

我有一个场景,我上传一个文本文件,然后提供一个用户输入,然后根据用户输入进一步处理

示例文件:

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
代码:

try:
    import Tkinter as Tk
    import tkFileDialog as fileDialog
except ImportError:
    import tkinter as Tk
    fileDialog = Tk.filedialog

import datetime

def user_input():
current_date = my_entry.get()

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

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

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()
上面给出了总停机时间为

12 min from 07.11.2016 08:21:33
但在这里,我试图介绍日期的用户输入,例如,如果我想获得2016年11月9日的停机时间,那么它应该提示我选择一个日期,并且输出(总停机时间)应该来自所选日期

任何帮助都会很好

编辑1(添加o/p):

回溯:

Exception in Tkinter callback
Traceback (most recent call last):
 File "C:\Program Files (x86)\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
 File "C:/Users/angelina/Desktop/test2/tinkteruser.py", line 34, in read_data
t1 = datetime.datetime.strptime(dt1, "%d.%m.%Y %H:%M:%S")
File "C:\Program Files (x86)\Python36-32\lib\_strptime.py", line 565, in     _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "C:\Program Files (x86)\Python36-32\lib\_strptime.py", line 362, in _strptime
(data_string, format))
ValueError: time data 'able   22.06.2017 1' does not match format  '%d.%m.%Y %H:%M:%S

您可以读取一次文件并计算不同的日期

顺便说一句:作为扩展,它可以在
条目中获得几个日期(用空格或逗号分隔),并计算每个日期的
总数,或者在两个日期的范围内进行计算


read_data()
中,它加载所有数据并使用

datetime.datetime.strptime(date1 + ' ' + time1, "%d.%m.%Y %H:%M:%S")
calculate
中,它从
Entry
中获取数据,并使用文件中的数据和条目中的日期执行
processText()

它将带有数据的字符串从
条目
转换为
日期时间
。字符串可能有不正确的日期或未用尽的格式,因此我使用
try/except


它使用
t1您可以读取一次文件并计算不同的日期

顺便说一句:作为扩展,它可以在
条目中获得几个日期(用空格或逗号分隔),并计算每个日期的
总数,或者在两个日期的范围内进行计算


read_data()
中,它加载所有数据并使用

datetime.datetime.strptime(date1 + ' ' + time1, "%d.%m.%Y %H:%M:%S")
calculate
中,它从
Entry
中获取数据,并使用文件中的数据和条目中的日期执行
processText()

它将带有数据的字符串从
条目
转换为
日期时间
。字符串可能有不正确的日期或未用尽的格式,因此我使用
try/except



它使用
t1可能会创建两个函数-第一个函数仅用于将所有数据加载到内存9中,也许您可以将其保留为日期时间,而不是字符串,第二个函数用于根据
date
计算
total
。您可以使用
pandas
轻松地读取文件和搜索表中的数据。@furas我对python非常陌生,您能帮我吗?那太好了。还要添加的是,我是否会显示输出?回溯显示的是
'able 22.06.2017 1'
,因此文件中的数据不同,并且与切片
行[:4]
行[5:24]
行[27:46]不匹配
我有相同格式的相同数据,但日期和时间也不同。请注意,我的文件中有24小时格式的时间值。当我尝试提供一个日期范围时,会出现上述错误。此外,如果我选择并运行该文件并计算停机时间,则第二次在同一时间不允许我运行另一个文件,我需要关闭程序,然后再次运行新的文件停机时间计算可能创建两个函数-第一个函数仅用于将所有数据加载到内存9中,也许您可以将其保留为日期时间,而不是字符串,第二个函数用于根据
日期计算
总计。您可以使用
pandas
轻松地读取文件和搜索表中的数据。@furas我对python非常陌生,您能帮我吗?那太好了。还要添加的是,我是否会显示输出?回溯显示的是
'able 22.06.2017 1'
,因此文件中的数据不同,并且与切片
行[:4]
行[5:24]
行[27:46]不匹配
我有相同格式的相同数据,但日期和时间也不同。请注意,我的文件中有24小时格式的时间值。当我尝试提供一个日期范围时,会出现上述错误。此外,如果我选择并运行该文件并计算停机时间,则第二次在同一时间不允许我运行另一个文件,我需要关闭该程序,然后再次运行新的文件停机时间计算谢谢您的解决方案,但添加堆栈跟踪时会引发错误。之所以会出现错误,是因为您的文件中存在与示例文件不同的内容。然后它不适合切片
行[:4]。strip()
行[5:24]
行[27:46]
。我的示例文件不是固定的。它可以有不同的值,因此如果我想在3个月的日期范围内搜索,例如2017年10月9日到2017年1月9日,那么它将不起作用?如果您的值不同于
“DOWN”
“UP”
(带2个空格)-那么日期在字符串中的不同位置,切片将不起作用,您必须使用
split()
与第一个版本类似。我更改了第二个代码-它再次使用
split()
而不是
slicing
。我将
.strftime(“%d.%m.%Y%H:%m:%S”)
返回总计,开始.strftime(“%d.%m.%Y%H:%m:%S”)
移动到
开始=t1.strftime(“%d.%m.%Y%H:%m:%S”)
感谢您的解决方案,但在添加堆栈跟踪时出现了一个错误。您会遇到错误,因为您的文件中有一些不同的内容,然后您将其视为示例文件。然后它不适合切片
行[:4]。strip()
行[5:24]
行[27:46]
。我的示例文件不是固定的。它可以有不同的值,因此如果我想在3个月的日期范围内搜索,例如2017年10月9日到2017年1月9日,那么它将不起作用?如果您的值不同于
“DOWN”
“UP”
(带2个空格)-那么日期在字符串中的不同位置,切片将不起作用,您必须使用
split()
与第一个版本类似。我更改了第二个代码-它再次使用
split()
而不是
slicing
。我将
.strftime(“%d.%m.%Y%H:%m:%S”)
返回总计,开始.strftime(“%d.%m.%Y%H:%m:%S”)
移动到
开始=t1.strftime(“%d.%m.%Y%H:%m:%S”)
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
try:
    import Tkinter as Tk
    import tkFileDialog as fileDialog
except ImportError:
    import tkinter as Tk
    import tkinter.filedialog as fileDialog

import datetime



def read_data():
    '''
    Read data from file and convert to list with datetime
    which can be used to calculate time and display.
    '''
    global data

    filename = fileDialog.askopenfilename()

    if filename:
        # read all lines
        with open(filename) as fileHandle:
            lines = fileHandle.readlines()

        # convert to `datetime` (not `timestamp`)
        data = []        
        for line in lines:
            #direction = line[:4].strip()
            #dt1 = line[5:24]
            #dt2 = line[27:46]

            direction, d1, t1, _, d2, t2 = line.split()
            dt1 = d1 + ' ' + t1
            dt2 = d2 + ' ' + t2 

            t1 = datetime.datetime.strptime(dt1, "%d.%m.%Y %H:%M:%S")
            t2 = datetime.datetime.strptime(dt2, "%d.%m.%Y %H:%M:%S")

            seconds = (t2-t1).seconds

            data.append([direction, t1, t2, seconds])

        print(data)


def processText(lines, selected_date):

    total = 0
    start = None

    print(selected_date)
    # if there is `selected_date` then convert to `datetime`
    if selected_date:
        try:
            selected_date = datetime.datetime.strptime(selected_date, "%d.%m.%Y")
        except AttributeError as ex:
            print("ERROR:", ex)
            selected_date = None

    # calculate time
    for direction, t1, t2, seconds in lines:

        if direction == "DOWN":

            # if `selected_date` then filter times
            if selected_date and t1 <= selected_date:
                continue

            if not start:
                start = t1.strftime("%d.%m.%Y %H:%M:%S")

            total += seconds

    # convert to minutes after summing all second
    total = total//60

    return total, start

def calculate():

    all_dates = entry.get().split(',')
    print(all_dates)
    all_dates = [date.strip() for date in all_dates]

    txt = ''

    for current_date in all_dates:
        down, start = processText(data, current_date)
        txt += "Total Downtime is {0} min from {1}\n".format(down, start)

    textVar.set(txt)

# --- main ---

data = None # to keep data from file

# -

root = Tk.Tk()

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

textVar = Tk.StringVar(root)

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

entry = Tk.Entry(root)
entry.grid(column=1, row=3)

button2 = Tk.Button(root, text="Calculate", command=calculate)
button2.grid(column=1, row=4)

root.mainloop()