我对Python完全陌生,我想创建一个简单的脚本,在一个文件中找到一个特定的值,然后用它执行一些计算。在
所以我有一个.gcode文件(它是一个3D打印机的数千行的文件,但是它可以被任何简单的文本编辑器打开)。我想创建一个简单的Python程序,当您启动它时,会打开一个简单的GUI,按钮要求选择一个.gcode文件。然后在文件被打开后,我希望程序找到具体的行; filament used = 22900.5mm (55.1cm3)
(上面是文件中该行的确切格式)并从中提取值55.1。稍后我想用这个值做一些简单的计算。我可以用一个简单的图形用户界面(GUI)把它用在一个简单的文件里,这样我就可以打开这个文件了。在
我希望我已经把我的问题解释清楚了,以便有人能帮我:)提前谢谢你的帮助!在
目前我的代码:from tkinter import *
import re
# Here, we are creating our class, Window, and inheriting from the Frame
# class. Frame is a class from the tkinter module. (see Lib/tkinter/__init__)
class Window(Frame):
# Define settings upon initialization. Here you can specify
def __init__(self, master=None):
# parameters that you want to send through the Frame class.
Frame.__init__(self, master)
#reference to the master widget, which is the tk window
self.master = master
#with that, we want to then run init_window, which doesn't yet exist
self.init_window()
#Creation of init_window
def init_window(self):
# changing the title of our master widget
self.master.title("Used Filament Data")
# allowing the widget to take the full space of the root window
self.pack(fill=BOTH, expand=1)
# creating a menu instance
menu = Menu(self.master)
self.master.config(menu=menu)
# create the file object)
file = Menu(menu)
# adds a command to the menu option, calling it exit, and the
# command it runs on event is client_exit
file.add_command(label="Exit", command=self.client_exit)
#added "file" to our menu
menu.add_cascade(label="File", menu=file)
#Creating the button
quitButton = Button(self, text="Load GCODE",command=self.read_gcode)
quitButton.place(x=0, y=0)
def get_filament_value(self, filename):
with open(filename, 'r') as f_gcode:
data = f_gcode.read()
re_value = re.search('filament used = .*? \(([0-9.]+)', data)
if re_value:
value = float(re_value.group(1))
else:
print 'filament not found in {}'.format(root.fileName)
value = 0.0
return value
print get_filament_value('test.gcode')
def read_gcode(self):
root.fileName = filedialog.askopenfilename( filetypes = ( ("GCODE files", "*.gcode"),("All files", "*.*") ) )
self.value = self.get_filament_value(root.fileName)
def client_exit(self):
exit()
# root window created. Here, that would be the only window, but
# you can later have windows within windows.
root = Tk()
root.geometry("400x300")
#creation of an instance
app = Window(root)
#mainloop
root.mainloop()