我创建了一个GUI,我在其中读取CSV文件,然后计算液体输出。在 CSVImport 功能中,有一个打印语句,其中计算输出。我想在我的GUI中使用文本小部件打印它。我怎样才能做到这一点?我的代码如下:
import csv
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showwarning, showinfo
import datetime
#csv_file = csv.reader(open("C:\Users\Lala Rushan\Downloads\ARIF Drop Monitoring Final\ARIF Drop Monitoring Final\DataLog.csv"))
from Tools.scripts.treesync import raw_input
class App(Frame):
def __init__(self, master):
Frame.__init__(self, master)
button1 = Button(self, text="Browse for a file", command=self.askfilename)
button2 = Button(self, text="Measure The Urine", command=self.takedate)
button3 = Button(self, text="Exit", command=master.destroy)
button1.grid()
button2.grid()
button3.grid()
l1 = Label(self, text="Enter from date (2017/01/01)")
l1.grid()
self.userInputFromRaw = Entry(self)
self.userInputFromRaw.grid()
l2 = Label(self, text="Enter to date (2017/01/01)")
l2.grid()
self.userInputToRaw = Entry(self)
self.userInputToRaw.grid()
self.grid()
def askfilename(self):
in_file = askopenfilename()
if not in_file.endswith(('.CSV')):
showwarning('Are you trying to annoy me?', 'How about giving me a CSV file, genius?')
else:
self.in_file=in_file
def CsvImport(self,csv_file):
dist = 0
for row in csv_file:
_dist = row[0]
try:
_dist = float(_dist)
except ValueError:
_dist = 0
dist += _dist
print ("Urine Volume is: %.2f" % (_dist*0.05))
def takedate(self):
from_raw = self.userInputFromRaw.get()
from_date = datetime.date(*map(int, from_raw.split('/')))
print ('From date: = ' + str(from_date))
to_raw = self.userInputToRaw.get()
to_date = datetime.date(*map(int, to_raw.split('/')))
in_file = ("H:\DataLog.csv")
in_file= csv.reader(open(in_file,"r"))
for line in in_file:
_dist = line[0]
try:
file_date = datetime.date(*map(int, line[1].split(' ')[1].split('/')))
if from_date <= file_date <= to_date:
self.CsvImport(in_file)
except IndexError:
pass
root = Tk()
root.title("Urine Measurement")
root.geometry("500x500")
app = App(root)
root.mainloop()
答案 0 :(得分:0)
首先,您必须拥有Text小部件。在App.__init__
函数中,您应该添加如下内容:
self.output = Text(self)
self.output.grid()
要将文字追加到窗口小部件,您可以使用Text.insert
;在App.CsvImport
函数中,您应该将对print
的调用替换为:
self.output.insert(END, "Urine Volume is: %.2f" % (_dist*0.05))
如果您需要对Tkinter文本小组件进行一些参考,this可能会有所帮助,以及StackOverflow上的各种问题。
值得注意的是,由于您只显示一行,因此使用Label
可能更方便。正常创建标签,当您想要更改文本时,可以使用:
self.output["text"] = "Urine Volume is: %.2f" % (_dist*0.05)