简体   繁体   English

如何在tkinter窗口中显示变量?

[英]How to display the variable in a tkinter window?

I am completely new to Python and I am working on a following code that I made with big help of fellow stackflow user. 我对Python完全陌生,我正在研究以下代码,这些代码是在stackflow用户的大力帮助下编写的。

After running the script a tkinter window open where you can select a gcode file (it is a file with many many lines of instructions for a 3D printer) and later a specific value from this file is found. 运行脚本后,将打开一个tkinter窗口,您可以在其中选择一个gcode文件(该文件包含3D打印机的许多指令行),然后从该文件中找到一个特定值。

What I would like to achieve is to: 我想实现的目标是:

1) Display this value under the load GCODE button in a tkinter window with a description/label. 1)在tkinter窗口的“加载GCODE”按钮下显示此值,并提供说明/标签。

2) Make some calculations on this value and display them in the tkinter window too. 2)对此值进行一些计算,并将其显示在tkinter窗口中。

3) Finaly make an executable of this script so everyone can use it, even without Python installed. 3)最后使该脚本成为可执行文件,以便每个人都可以使用它,即使没有安装Python。

I am not sure if this is super easy or it's a lot of work as I am completely new to Python (and not so good in programming overall). 我不确定这是否超级简单,还是需要大量工作,因为我是Python的新手(在整体编程上不太好)。 I hope I have explained things good enough and thank you in advance for any input! 希望我已经讲得足够好了,并在此先感谢您的投入!

Gcode file for code testing: GCODE FILE 用于代码测试的Gcode文件GCODE FILE

Finaly the code: 完成代码:

from tkinter import *
import re
from tkinter import messagebox
from tkinter import filedialog

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

    # Load the gcode file in and extract the filament value
    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))
                return('Volume of the print is {} cm3'.format(value))
            else:
                value = 0.0
                return('Filament volume was not found in {}'.format(fileName))
        return value

    def read_gcode(self):
        root.fileName = filedialog.askopenfilename(filetypes = (("GCODE files", "*.gcode"), ("All files", "*.*")))
        self.value.set = self.get_filament_value(root.fileName)
#       self.value.set('Button pressed')

    def client_exit(self):
        exit()

    def about_popup(self):
        messagebox.showinfo("About", "Small software created by Bartosz Domagalski to find used filament parameters from Sli3er generated GCODE")

    #Creation of init_window
    def init_window(self):

        # changing the title of our master widget      
        self.master.title("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)
        help = 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)
        help.add_command(label="About", command=self.about_popup)

        #added "file" to our menu
        menu.add_cascade(label="File", menu=file)
        menu.add_cascade(label="Help", menu=help)


        #Creating the labels
        self.value = StringVar()
        l_instruction = Label(self, justify=CENTER, compound=TOP, text="Load GCODE file to find volume, \n weight and price of used filament.")
        l = Label(self, justify=CENTER, compound=BOTTOM, textvariable=self.value)
#       l.place(x=85, y=45)
        l_instruction.pack()
        l.pack()

        #Creating the button
        gcodeButton = Button(self, text="Load GCODE", command=self.read_gcode)
        gcodeButton.pack()
#       gcodeButton.place(x=140, y=10)

        #status Bar
        status = Label(self, text="Waiting for file...", bd=1, relief=SUNKEN, anchor=W)
        status.pack(side=BOTTOM, fill=X)

# root window created. Here, that would be the only window, but you can later have windows within windows.
root = Tk()
root.resizable(width=False,height=False);
root.geometry("220x300")


#creation of an instance
app = Window(root)

#mainloop 
root.mainloop()

You should put the Label(s) inside the same Frame as you have the button. 您应该将Label(s)放置在与按钮相同的Frame中。 And when I copied in your code I had to import the filedalog module as well ( from tkinter import filedalog ), the asterisk import didn't seem to cover it. 当我在您的代码中复制时,我也必须导入filedalog模块( from tkinter import filedalog ),星号导入似乎并没有覆盖它。

You could use a StringVar() variable (from tkinter) and assign it to the label. 您可以使用StringVar()变量(来自tkinter)并将其分配给标签。 This variable you can .set() and .get() values from. 您可以从中获取.set().get()值。 Create variable and assign it to Label: 创建变量并将其分配给Label:

self.value = StringVar('', value="  Load GCODE file to find volume, \n weight and price of used filament.")
l = Label(self, textvariable=self.value)

Alter variable value: 更改变量值:

self.value.set(self.get_filament_value(root.fileName))

The Label you will have to place as you want it, just like you did with the Button with quitButton.place . 您必须根据需要放置Label,就像使用quitButton.place的Button quitButton.place There are other ways to handle the layout, grid and pack. 还有其他方法可以处理布局,网格和打包。 But as far as I know, it is recommended to pick one layout style for all elements. 但据我所知,建议为所有元素选择一种布局样式。

Creating an executable, "freezing" your code, is a broader topic. 创建可执行文件,“冻结”您的代码,是更广泛的主题。 Take a look here for some options that you can look more into. 在这里查看一些可以进一步了解的选项。


edit: 编辑:

Updated working code. 更新了工作代码。 Changing the placement of widgets you'll figure out ;) Not looked at any new elements in your code. 改变小部件的位置,您会发现的;)没有查看代码中的任何新元素。

from tkinter import *
import re
from tkinter import messagebox, filedialog


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

    # Load the gcode file in and extract the filament value
    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))
                return 'Volume of the print is {} cm3'.format(value)
            else:
                return 'Filament volume was not found in {}'.format(fileName)

    def read_gcode(self):
        root.fileName = filedialog.askopenfilename(filetypes=(("GCODE files", "*.gcode"), ("All files", "*.*")))
        self.value.set(self.get_filament_value(root.fileName))

    def client_exit(self):
        exit()

    def about_popup(self):
        messagebox.showinfo("About",
                            "Small software created by Bartosz Domagalski to find used filament parameters from Sli3er generated GCODE")

    # Creation of init_window
    def init_window(self):

        # changing the title of our master widget
        self.master.title("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)
        help = 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)
        help.add_command(label="About", command=self.about_popup)

        # added "file" to our menu
        menu.add_cascade(label="File", menu=file)
        menu.add_cascade(label="Help", menu=help)

        # Creating the labels
        self.value = StringVar()
        l_instruction = Label(self, justify=CENTER, compound=TOP,
                              text="  Load GCODE file to find volume, \n weight and price of used filament.")
        l = Label(self, justify=CENTER, compound=BOTTOM, textvariable=self.value)
        #       l.place(x=85, y=45)
        l_instruction.pack()
        l.pack()

        l_instruction.pack()
        self.value = StringVar()
        l = Label(self, textvariable=self.value)
        l.pack()

        # Creating the button
        gcodeButton = Button(self, text="Load GCODE", command=self.read_gcode)
        gcodeButton.pack()
        #       gcodeButton.place(x=140, y=10)

        # status Bar
        status = Label(self, text="Waiting for file...", bd=1, relief=SUNKEN, anchor=W)
        status.pack(side=BOTTOM, fill=X)


# root window created. Here, that would be the only window, but you can later have windows within windows.
root = Tk()
root.resizable(width=False, height=False);
# root.geometry("400x300")


# creation of an instance
app = Window(root)

# mainloop
root.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM