Python>tkinter:如何从笔记本框架内的面板获取值

2024-10-01 17:32:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚开始用python编写程序,并用它制作一个带有GUI(使用tkinter)的小程序,它可以从excel文件(使用openpyxl)中获取数据。允许用户在必要时进行更改,然后使用按钮将条目中的数据写入数据文件(.dat)(最好是通过更新defaultdict数组中的值,然后写入.dat文件),并使用建模语言(pyomo)使用所提供的数据创建模型,并使用cbc解算器进行求解。在

我现在已经做了这个模型,图形界面(里面充满了excel文件中的数据)。但是,我无法将entries字段中的数据取回(以写入更新defaultdicts数组)。我理解stackoverflow的简单示例(使用入口.get()),但在我的示例中没有起作用(可能是因为我使用了notbook标签页、面板和框架,或者我搞错了什么)。在

我使用笔记本选项卡而不是一页,因为我将有更多(大约5)其他类别的数据在整个程序。最后我想让程序是这样一种方式,它可以适应输入(所以它不知道会有3,8或10个设施)。我使用python3.5.1版。以下是指向excel文件的链接:https://drive.google.com/file/d/0B5vmtJnltudJWW4xakZlYnQ3RTg/view?usp=sharing

    import sys
    from tkinter import ttk
    import tkinter as tk
    import openpyxl
    import numpy as np
    import os
    from collections import defaultdict
    from facility_panel import *

    class App(tk.Tk):


        def __init__(self):
            tk.Tk.__init__(self)
            self.getdata()
            self.tabes()
            button_box = tk.Frame(self)
            tk.Button(button_box, text='Create Planning', command=self.on_ok_clicked).grid(pady=15)
            button_box.pack()

            self.create_menu()
            self.set_keybindings()

        @staticmethod
        def center_on_screen(toplevel):
            toplevel.update_idletasks()
            w = toplevel.winfo_screenwidth()
            h = toplevel.winfo_screenheight()
            size = tuple(int(_) for _ in toplevel.geometry().split('+')[0].split('x'))
            x = w/2 - size[0]/2
            y = h/2 - size[1]/2
            toplevel.geometry('%dx%d+%d+%d' % (size + (x, y)))


        def set_keybindings(self):
            self.bind_all('<Control-o>', lambda event: self.open_file())
            self.bind_all('<Control-s>', lambda event: self.save_file())
            self.bind_all('<Control-q>', self.quit_app)
            self.bind_all('<Control-h>', lambda event: self.show_help())
            self.bind_all('<Return>', lambda event: self.on_ok_clicked())


        def on_ok_clicked(self):
            print ('Entry text: %s' % self.entry.get())
            print ('Scale value: %.1f' % self.scale.get())
            print ('Checkbutton value: %i' % self.checkbox_val.get())
            print ('Spinbox value: %i' % int(self.spinbox.get()))
            print ('OptionMenu value: %s' % self.enum_val.get()) 


        def create_menu(self):
            menubar = tk.Menu(self)

            fileMenu = tk.Menu(menubar, tearoff=False)
            menubar.add_cascade(label="File", underline=0, menu=fileMenu)
            fileMenu.add_command(label="Open", underline=1, command=self.open_file, accelerator="Ctrl+O")
            fileMenu.add_command(label="Save", underline=1, command=self.save_file, accelerator="Ctrl+S")
            fileMenu.add_command(label="Quit", underline=1, command=self.quit_app, accelerator="Ctrl+Q")

            helpMenu = tk.Menu(menubar, tearoff=False)
            menubar.add_cascade(label="Help", underline=0, menu=helpMenu)
            helpMenu.add_command(label="Help", underline=1, command=self.show_help, accelerator="Ctrl+H")
            helpMenu.add_command(label="About", underline=1, command=self.about_app)
            self.config(menu=menubar)


        def open_file(self):
            """Options are explained here: http://tkinter.unpythonic.net/wiki/tkFileDialog"""
            filename = askopenfilename(title='Open a file')
            if filename:
                print ('Open and do something with %s' % filename)


        def save_file(self):
            """Options are explained here: http://tkinter.unpythonic.net/wiki/tkFileDialog"""
            filename = asksaveasfilename()
            if filename:
                print ('Save something to %s' % filename)


        def quit_app(self):
            app.destroy()


        def show_help(self):
            # FIXME: pressing return correctly closes dialog, but also incorrectly fires the main window's 'on_click' method
            about_text = """
            Contact: \n
            example@hotmail.com"""
            about_dialog = tk.Toplevel(self)
            about_dialog.title('About App')
            about_dialog.bind('<Escape>', lambda event: about_dialog.destroy())
            about_dialog.bind('<Return>', lambda event: about_dialog.destroy())
            App.center_on_screen(about_dialog)
            tk.Message(about_dialog, text=about_text).pack()
            button = tk.Button(about_dialog, text='Close', command=about_dialog.destroy).pack()


        def about_app(self):
            # FIXME: pressing return correctly closes dialog, but also incorrectly fires the main window's 'on_click' method
            about_text = """
            This application is made by Jan Jansen\n
            version 0.7"""
            about_dialog = tk.Toplevel(self)
            about_dialog.title('About App')
            about_dialog.bind('<Escape>', lambda event: about_dialog.destroy())
            about_dialog.bind('<Return>', lambda event: about_dialog.destroy())
            App.center_on_screen(about_dialog)
            tk.Message(about_dialog, text=about_text).pack()
            button = tk.Button(about_dialog, text='Close', command=about_dialog.destroy).pack()

        def tabes(self):
            nb = ttk.Notebook()
            nb.pack(expand=1, fill="both")


                    # Frame to hold contentx
            frame = tk.Frame(nb)

            vscroll = tk.Scrollbar(frame, orient="vertical")
            #panel['yscroll'] = vscroll.set
            vscroll.pack(side="right", fill="y")

            for facilityname in Facilities:
                panel = FacilityPanel(frame, facilityname, capfacility[facilityname], safetystock[facilityname], maxpressure[facilityname], str(compulsorystarttime[facilityname]),  str(compulsoryendtime[facilityname]), demandmatrix[facilityname][1], demandmatrix[facilityname][2], demandmatrix[facilityname][3], demandmatrix[facilityname][4], demandmatrix[facilityname][5], demandmatrix[facilityname][6], demandmatrix[facilityname][7])
                panel.pack(fill="both")


            # add to notebook (underline = index for short-cut character)
            nb.add(frame, text='Facilities', underline=0, padding=2)


    #--------------------------------------------------------------------------------------------------------
        def getdata(self):
                wb = openpyxl.load_workbook("data.xlsx")


                ws = wb["Facilities"]
                global Facilities
                Facilities = ([])
                row_count = ws.max_row
                column_count = ws.max_column
                global initlevel
                initlevel = defaultdict(dict)
                global capfacility
                capfacility = defaultdict(dict)
                global safetystock
                safetystock = defaultdict(dict)
                global maxpressure
                maxpressure = defaultdict(dict)
                global pressureincrease
                pressureincrease = defaultdict(dict)
                global compulsorystarttime
                compulsorystarttime = defaultdict(dict)
                global compulsoryendtime
                compulsoryendtime = defaultdict(dict)
                global demandmatrix
                demandmatrix = defaultdict(dict)
                for i in range(3, row_count+1, 1):
                      Facilities.append(ws.cell(row = i, column = 1).value)
                      initlevel[ws.cell(row = i, column = 1).value]  = ws.cell(row = i, column = 2).value
                      capfacility[ws.cell(row = i, column = 1).value]  = ws.cell(row = i, column = 3).value
                      safetystock[ws.cell(row = i, column = 1).value]  = ws.cell(row = i, column = 4).value
                      maxpressure[ws.cell(row = i, column = 1).value]  = ws.cell(row = i, column = 5).value
                      pressureincrease[ws.cell(row = i, column = 1).value]  = ws.cell(row = i, column = 6).value
                      compulsorystarttime[ws.cell(row = i, column = 1).value]  = ws.cell(row = i, column = 7).value
                      compulsoryendtime[ws.cell(row = i, column = 1).value]  = ws.cell(row = i, column = 8).value
                      for j in range (9, column_count+1, 1):
                         demandmatrix[ws.cell(row = i, column = 1).value][ws.cell(row = 2, column = j).value] = ws.cell(row = i, column = j).value


    if __name__ == "__main__":
        app = App()
        app.title("Planning")
        toplevel = app.winfo_toplevel()
        toplevel.wm_state('zoomed')
        app.mainloop()

这是我上的课: 来自tkinter import*

^{pr2}$

Tags: textselfappwsvaluedefcellcolumn

热门问题