如何一次从多个Tkinter GUI窗口写入一个Excel文件?

时间:2019-03-04 07:27:00

标签: python excel tkinter xlwt

我是Tkinter的新手。尝试使用以下方法将我的多个tkinter GUI的用户输入写入Excel文件,但是最新值仍然被覆盖。我无法将以前的输入值从用户保留到Excel。在这里请求您的帮助。我已经使用numofvm()创建了多个tkinter窗口,因此将创建GUI,然后在用户通过GUI输入值之后。

QR Code

1 个答案:

答案 0 :(得分:1)

正如我在评论中解释的那样,数据写入问题是因为您需要存储StringVar,而相关信息是list s,而不是仅使用单个值来覆盖以前的值变量。

尽管不这样做就可以修复,但是您使用了如此多的全局变量会使代码难以理解,调试和修改,这都是人们普遍认为尽可能避免使用它们的原因。

以下是您的问题中的代码使用的列表:

cluster_nameclustername_entryvm_templatevmdetails_screeninvalid_value_screennumofvm_screenvmnumbervmnumber_entryNmain_screen

由于数量很多,因此我决定在下面的代码中也消除它们,以使设计“更整洁”,除了仅按照建议显示如何将数据存储在list中。希望这将为您继续开发应用程序提供更好的基础。

为避免使用global,大多数变量已变成代表整个应用程序的类的属性,该属性是基于this answer并由tkinter提出tkinter问题的设计大师@Bryan Oakley。

from tkinter import *
import tkinter.messagebox as tkMessageBox
import os
import xlwt


class MyApp(Tk):
    LABEL_BG = "light blue"

    def __init__(self):
        Tk.__init__(self)
        self.geometry("300x250")
        self.title("Welcome")
        Label(text="Select Your Choice", bg=self.LABEL_BG, width="300", height="2",
              font=("Calibri", 13)).pack()
        Label(text="").pack()
        Button(text="Enter", height="2", width="30", command=self.numofvm).pack()
        Label(text="").pack()

    def numofvm(self):
        """ Designing window to provide the number of VMs to be created. """
        self.numofvm_screen = Toplevel(self)
        self.numofvm_screen.title("VM_NUM")
        self.numofvm_screen.geometry("300x250")

        self.vmnumber = StringVar()

        Label(self.numofvm_screen,
              text="Please enter the Number of VMs you wishes to create",
              bg=self.LABEL_BG).pack()
        Label(self.numofvm_screen, text="").pack()

        vmnumber_lable = Label(self.numofvm_screen,
                               text="Number of VMs to be created:")
        vmnumber_lable.pack()

        self.vmnumber_entry = Entry(self.numofvm_screen, textvariable=self.vmnumber)
        self.vmnumber_entry.pack()

        Button(self.numofvm_screen, text="Submit", width=10, height=1,
               command=self.screen_duplicate).pack()

        self.numofvm_screen.focus_set()

    def screen_duplicate(self):
        try:
            self.N = int(self.vmnumber.get())
        except ValueError:
            self.N = 0

        if self.N > 0:
            self.vm_details()

    def vm_details(self):
        """ Create designing windows for VM details.
        """
        # Preallocate and then create VM detail screens and data.
        self.cluster_names = [None for _ in range(self.N)]
        self.clustername_entries = [None for _ in range(self.N)]
        self.vm_templates = [None for _ in range(self.N)]
        self.vmdetails_screen = [None for _ in range(self.N)]

        for i in range(self.N):
            numb = str(i+1)
            self.vmdetails_screen[i] = Toplevel()
            self.vmdetails_screen[i].title("VM Details " + numb)
            self.vmdetails_screen[i].geometry("400x950")

            # Set text variables
            self.cluster_names[i] = StringVar()
            self.vm_templates[i] = StringVar()

            # Set label for user's instruction
            Label(self.vmdetails_screen[i], text="Please enter details below:",
                  bg=self.LABEL_BG).pack()
            Label(self.vmdetails_screen[i], text="").pack()

            Cluster_Name_lable = Label(self.vmdetails_screen[i],
                                       text="Cluster Name "+ numb + ":")
            Cluster_Name_lable.pack()

            # Set textvariables entry
            self.clustername_entries[i] = Entry(self.vmdetails_screen[i],
                                                textvariable=self.cluster_names[i])
            self.clustername_entries[i].pack()

            Button(self.vmdetails_screen[i], text="Submit", width=10, height=1,
                   command=self.validate).pack()

    def validate(self):
        """ Check values of ALL cluster name entries and save them to excel
            file if they're all valid.
        """
        if not all(cluster_name.get() for cluster_name in self.cluster_names):
            self.invalid_value()
        else:
            self.write_to_xls()
            tkMessageBox.showinfo("Info", '"%s" file written' % self.xls_filepath)

            # Get rid of all data entry screens.
            for i in range(self.N):
                self.vmdetails_screen[i].destroy()

            self.numofvm_screen.destroy()

    def invalid_value(self):
        """ Display error message screen.
        """
        self.invalid_value_screen = Toplevel()
        self.invalid_value_screen.title("Invalid Entry")
        self.invalid_value_screen.geometry("400x100")
        Label(self.invalid_value_screen,
              text="Please enter valid values for the fields in ALL\n"
                   "VM Detail windows before clicking Submit button").pack()
        Button(self.invalid_value_screen, text="OK",
               command=lambda: self.invalid_value_screen.destroy()).pack()

    def write_to_xls(self):
        """ Export all user's inputs to an excel sheet. """

        # Create new workbook.
        wb = xlwt.Workbook()

        for i in range(self.N):
            numb = str(i+1)
            # Add sheet using given name.
            ws = wb.add_sheet("VM_" + numb + "_DETAILS")

            # Write text to cell.
            ws.write(0, 0, "Cluster_Name")
            ws.write(1, 0, self.cluster_names[i].get())

        # Save excel file in same directory as script.
        self.xls_filepath = os.path.join(os.path.dirname(__file__), 'my_file.xls')
        wb.save(self.xls_filepath)


if __name__ == '__main__':
    root = MyApp()
    root.mainloop()