I've got a problem with a part of my code. It's about partial searching in treeview. I found here on stack overflow partial search method and tried to use with my code. It does't work - It doesn't give any results. Code here below:
from tkinter import *
from tkinter import ttk
root = Tk()
sv = StringVar()
ids = []
names = []
def add():
names = tree.insert("",END,values=(e0.get(),e1.get(),e2.get(),e3.get()))
for i in range(len(names)):
ids.append(tree.insert("", "end", text=names[i]))
def command(*args):
selections = []
for i in range(len(names)):
if entry.get() != "" and entry.get() == names[i][:len(entry.get())]:
selections.append(ids[i])
tree.selection_set(selections)
sv.trace("w", command)
entry = Entry(root, textvariable=sv,width=13)
entry.grid(row=2,column=1,rowspan=3,sticky=W)
e0 = Entry(root,width=15)
e0.grid(row=0,column=1,rowspan=1,sticky=W)
e1 = Entry(root,width=15)
e1.grid(row=0,column=1,rowspan=2,sticky=W)
e2 = Entry(root,width=15)
e2.grid(row=0,column=1,rowspan=3,sticky=W)
e3 = Entry(root,width=15)
e3.grid(row=0,column=1,rowspan=4,sticky=W)
btn1 = Button(root,text="add",width=5,command=add)
btn1.grid(row =0,column=0,rowspan=5)
lb1 = Label(root,text="serial num:")
lb1.grid(row =0,column=0,rowspan=1)
lb2 = Label(root,text="medicine\nname ")
lb2.grid(row =0,column=0,rowspan=2)
lb3 = Label(root,text="quatity")
lb3.grid(row =0,column=0,rowspan=3)
lb4 = Label(root,text="expiry Date")
lb4.grid(row =0,column=0,rowspan=4)
lb4 = Label(root,text="search box")
lb4.grid(row =1,column=0,rowspan=6)
#treeview
tree = ttk.Treeview(root,height=25)
tree["columns"]=("one","two","three","four")
tree.column("one",width=120)
tree.column("two",width=160)
tree.column("three",width=130)
tree.column("four",width=160)
tree.heading("one", text="Numer seryjny leku")
tree.heading("two", text="Nazwa Leku")
tree.heading("three", text="Ampułki/Tabletki")
tree.heading("four",text="Data ważności")
tree["show"]="headings"
tree.grid(row=0,column=2,rowspan=6,pady=20)
root.geometry("840x580")
root.mainloop()
The variable names is not defined. You should put a similar line to the following one in the beginning of your code:
names = []
On the other hand, you have to declare the command function as follows to make it work, since the trace callback expects at least three arguments:
def command(*args):
By the way, if you do not want to loose the data in variable names, I would transform your code in a class-oriented way, such as the following one:
from tkinter import *
from tkinter import ttk
root = Tk()
sv = StringVar()
ids = []
class Tree():
def __init__(self, root):
self.names = []
sv.trace("w", self.command)
self.entry = Entry(root, textvariable=sv, width=13)
self.entry.grid(row=2,column=1,rowspan=3,sticky=W)
self.e0 = Entry(root,width=15)
self.e0.grid(row=0,column=1,rowspan=1,sticky=W)
self.e1 = Entry(root,width=15)
self.e1.grid(row=0,column=1,rowspan=2,sticky=W)
self.e2 = Entry(root,width=15)
self.e2.grid(row=0,column=1,rowspan=3,sticky=W)
self.e3 = Entry(root,width=15)
self.e3.grid(row=0,column=1,rowspan=4,sticky=W)
self.btn1 = Button(root,text="add",width=5,command=self.add)
self.btn1.grid(row =0,column=0,rowspan=5)
self.lb1 = Label(root,text="serial num:")
self.lb1.grid(row =0,column=0,rowspan=1)
self.lb2 = Label(root,text="medicine\nname ")
self.lb2.grid(row =0,column=0,rowspan=2)
self.lb3 = Label(root,text="quatity")
self.lb3.grid(row =0,column=0,rowspan=3)
self.lb4 = Label(root,text="expiry Date")
self.lb4.grid(row =0,column=0,rowspan=4)
self.lb4 = Label(root,text="search box")
self.lb4.grid(row =1,column=0,rowspan=6)
#treeview
self.tree = ttk.Treeview(root,height=25)
self.tree["columns"]=("one","two","three","four")
self.tree.column("one",width=120)
self.tree.column("two",width=160)
self.tree.column("three",width=130)
self.tree.column("four",width=160)
self.tree.heading("one", text="Numer seryjny leku")
self.tree.heading("two", text="Nazwa Leku")
self.tree.heading("three", text="Ampułki/Tabletki")
self.tree.heading("four",text="Data ważności")
self.tree["show"]="headings"
self.tree.grid(row=0,column=2,rowspan=6,pady=20)
def add(self):
self.names = self.tree.insert("",END,values=(self.e0.get(),self.e1.get(),self.e2.get(),self.e3.get()))
for i in range(len(self.names)):
ids.append(self.tree.insert("", "end", text=self.names[i]))
def command(self, *args):
selections = []
for i in range(len(self.names)):
if self.entry.get() != "" and self.entry.get() == self.names[i][:len(self.entry.get())]:
selections.append(ids[i])
self.tree.selection_set(selections)
tree = Tree(root)
root.geometry("840x580")
root.mainloop()
Related
Here's my code of a gui app using tkinter library, it creats tables and prints orders for each table and gives the ability to edit orders on every table. the goal of it to know what did each table order. but editing the orders doesn't seem to work at all, I need help fixing it.
import tkinter as tk
class TableOrdersApp:
def __init__(self, master):
self.tables = []
self.table_list = tk.Listbox(master)
self.table_list.pack(side=tk.LEFT, fill=tk.BOTH)
self.table_list.bind("<<ListboxSelect>>", self.refresh_label)
self.orders_label = tk.Label(master, text="", anchor=tk.W, justify=tk.LEFT, wraplength=400)
self.orders_label.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
self.button_frame = tk.Frame(master)
self.button_frame.pack(side=tk.RIGHT)
self.add_button = tk.Button(self.button_frame, text="Add Table", command=self.add_table)
self.add_button.pack(side=tk.TOP)
self.remove_button = tk.Button(self.button_frame, text="Remove Table", command=self.remove_table)
self.remove_button.pack(side=tk.TOP)
self.edit_button = tk.Button(self.button_frame, text="Edit Order", command=self.edit_order)
self.edit_button.pack(side=tk.TOP)
self.remove_order_button = tk.Button(self.button_frame, text="Remove Order", command=self.remove_order)
self.remove_order_button.pack(side=tk.TOP)
def add_table(self):
self.tables.append([])
self.table_list.insert(tk.END, "Table {}".format(len(self.tables)))
def remove_table(self):
index = self.table_list.curselection()[0]
self.tables.pop(index)
self.table_list.delete(index)
def refresh_label(self, event=None):
self.orders_label.config(text="\n".join(self.tables[self.table_list.curselection()[0]]))
def edit_order(self):
index = self.table_list.curselection()[0]
orders = self.tables[index]
if self.orders_label.select_present():
start_index = self.orders_label.index(tk.SEL_FIRST)
end_index = self.orders_label.index(tk.SEL_LAST)
selected_text = self.orders_label.selection_get()
num_newlines = selected_text.count("\n")
order_index = start_index.split(".")[0] - 1 - num_newlines
new_order = tk.simpledialog.askstring("Edit Order", "Enter the new order:")
orders[order_index] = new_order
self.refresh_label()
def remove_order(self):
index = self.table_list.curselection()[0]
orders = self.tables[index]
start_index = self.orders_label.index(tk.SEL_FIRST)
end_index = self.orders_label.index(tk.SEL_LAST)
num_newlines = self.orders_label.get(start_index, end_index).count("\n")
order_index = start_index.split(".")[0] - 1 - num_newlines
orders.pop(order_index)
self.refresh_label()
# Create the main window
root = tk.Tk()
# Create an instance of the TableOrdersApp class
app = TableOrdersApp(root)
# Run the main loop of the app
root.mainloop()
I tried to make it print a label and make it editable using "edit order" button, but the button itself doesn't seem to work, and I want it to print "Empty" if the table has no orders how can i do that.
Look in edit_order and remove_order function. Must easier to write less coding.
Here is code:
import tkinter as tk
class TableOrdersApp:
def __init__(self, master):
self.tables = []
self.table_list = tk.Listbox(master)
self.table_list.pack(side=tk.LEFT, fill=tk.BOTH)
self.table_list.bind("<<ListboxSelect>>", self.refresh_label)
self.orders_label = tk.Label(master, text="", anchor=tk.W, justify=tk.LEFT, wraplength=400)
self.orders_label.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
self.button_frame = tk.Frame(master)
self.button_frame.pack(side=tk.RIGHT)
self.add_button = tk.Button(self.button_frame, text="Add Table", command=self.add_table)
self.add_button.pack(side=tk.TOP)
self.remove_button = tk.Button(self.button_frame, text="Remove Table", command=self.remove_table)
self.remove_button.pack(side=tk.TOP)
self.edit_button = tk.Button(self.button_frame, text="Edit Order", command=self.edit_order)
self.edit_button.pack(side=tk.TOP)
self.remove_order_button = tk.Button(self.button_frame, text="Remove Order", command=self.remove_order)
self.remove_order_button.pack(side=tk.TOP)
def add_table(self):
self.tables.append([])
self.table_list.insert(tk.END, "Table {}".format(len(self.tables)))
def remove_table(self):
index = self.table_list.curselection()[0]
self.tables.pop(index)
self.table_list.delete(index)
def refresh_label(self, event=None):
self.orders_label.config(text="\n".join(self.tables[self.table_list.curselection()[0]]))
def edit_order(self):
index = self.table_list.curselection()[0]
orders = self.table_list.get(index)
print(index)
order = orders
self.orders_label.configure(text=order)
#if self.orders_label.select_present():
#start_index = self.orders_label.index(tk.SEL_FIRST)
#end_index = self.orders_label.index(tk.SEL_LAST)
#selected_text = self.orders_label.selection_get()
#num_newlines = selected_text.count("\n")
#order_index = start_index.split(".")[0] - 1 - num_newlines
#new_order = tk.simpledialog.askstring("Edit Order", "Enter the new order:")
#orders[order_index] = new_order
#self.refresh_label()
def remove_order(self):
remove_orders = self.table_list.curselection()
self.table_list.delete(remove_orders)
self.orders_label.configure(text="")
#index = self.table_list.curselection()[0]
#orders = self.tables[index]
#start_index = self.orders_label.index(tk.SEL_FIRST)
#end_index = self.orders_label.index(tk.SEL_LAST)
#num_newlines = self.orders_label.get(start_index, end_index).count("\n")
#order_index = start_index.split(".")[0] - 1 - num_newlines
#orders.pop(order_index)
#self.refresh_label()
# Create the main window
root = tk.Tk()
# Create an instance of the TableOrdersApp class
app = TableOrdersApp(root)
# Run the main loop of the app
root.mainloop()
Result when executes:
Result when selected:
Result when removed order:
I am using Tkinter/Python to get the selected option on the window when the button is pressed. On clicking the button - only the value from list should get printed. As of now, it's printing any value typed into combobox. Any help/suggestion will be appreciated.
from tkinter import *
from tkinter import ttk
class Run:
def __init__(self, master):
self.lst = ["Apples", "Oranges", "Pears", "Grapes"]
self.master = master
self.toplevels = 0
master.title("CB")
master.geometry("300x200")
label = Label(master, text = "ABC")
label.pack()
self.combo_box = ttk.Combobox(master,value=self.lst)
self.combo_box.set('')
self.combo_box.pack()
self.combo_box.bind('<KeyRelease>', self.search)
button = Button(master, text="btn", command=self.make_new)#self.make_new)
button.pack()
def make_new(self):
if not self.toplevels:
#new = tk.Toplevel(self.master)
my_label = Label(self.master, text=self.combo_box.get(), font=("Helvetica", 14))#, fg="grey")
my_label.pack(padx=10, pady=10)
self.toplevels += 1
def search(self, event):
value = event.widget.get()
if value == '':
self.combo_box['values'] = self.lst
else:
data = []
for item in self.lst:
if value.lower() in item.lower():
data.append(item)
self.combo_box['values'] = data
master1 = Tk()
i = Run(master1)
master1.mainloop()
The answer is simple. You just have to a condition which will detect if the text of the combo box is in the list or not. That condition would be: if self.combo_box.get() in self.lst:. And for the corrected code:
from tkinter import *
from tkinter import ttk
class Run:
def __init__(self, master):
self.my_label = Label(master, text="")
self.lst = ["Apples", "Oranges", "Pears", "Grapes"]
self.master = master
self.toplevels = 0
master.title("CB")
master.geometry("300x200")
label = Label(master, text="ABC")
label.pack()
self.combo_box = ttk.Combobox(master, value=self.lst)
self.combo_box.set('')
self.combo_box.pack()
self.combo_box.bind('<KeyRelease>', self.search)
button = Button(master, text="btn", command=self.make_new) # self.make_new)
button.pack()
def make_new(self):
if not self.toplevels:
# new = tk.Toplevel(self.master)
if self.combo_box.get() in self.lst:
self.my_label.config(text=self.combo_box.get(), font=("Helvetica", 14)) # , fg="grey")
self.my_label.pack(padx=10, pady=10)
self.toplevels += 1
def search(self, event):
value = event.widget.get()
if value == '':
self.combo_box['values'] = self.lst
else:
data = []
for item in self.lst:
if value.lower() in item.lower():
data.append(item)
self.combo_box['values'] = data
master1 = Tk()
i = Run(master1)
master1.mainloop()
Hope this helps
I was really curious why I cannot get my add_button to work,
as the window fails to come up when creating it.
from tkinter import *
class Calculator:
#-------------------------------------------------
def __init__(self, master):
self.master = master
master.title("Calculator")
self.close_button = Button(master, text = "Close", command = master.destroy)
Label(master, text = "First Digit").grid(row = 0)
Label(master, text = "Second Digit").grid(row = 1)
self.input1 = 0
self.input2 = 0
input1 = Entry(master)
input2 = Entry(master)
input1.grid(row = 0, column = 1)
input2.grid(row = 1, column = 1)
self.close_button.grid(row = 2, column = 0)
self.add_buton = Button(master, text = "Add", command = self.add())
self.add_button.grid(row = 2, column = 1)
master.configure(background = 'grey')
return
#-------------------------------------------------
def add(self):
return self.input1.get() + self.input2.get()
#-------------------------------------------------
#-------------------------------------------------
root = Tk()
calc = Calculator(root)
root.mainloop()
#-------------------------------------------------
Welcome to Stack!
I've looked through you code I've been able to do what you are asking. There were a few errors within your code:
a) you had self.add_buton and self.add_button which caused an error.
b) self.input1 = 0 and self.input2 = 0 are not required.
c) You were calling self.add() as the command and you should be calling self.add. When calling it as a command you do not need ()
d)input1 = Entry(master) should be self.input1 = tk.Entry(master)
e) You should convert your input values into int or float as otherwise it will just one value onto the end of the other. (Eg, 1 + 5 = 15 whereas int(1) + int(5) = 6
Here is your code with the entry boxes working as they should. I have import tkinter as tk hence why it is tk.Entry
from tkinter import *
import tkinter as tk
class Calculator:
#-------------------------------------------------
def __init__(self, master):
self.master = master
master.title("Calculator")
self.close_button = Button(master, text = "Close", command = master.destroy)
Label(master, text = "First Digit").grid(row = 0)
Label(master, text = "Second Digit").grid(row = 1)
self.input1 = tk.Entry(bd=5, width=35, background='gray35', foreground='snow')
self.input2 = tk.Entry(bd=5, width=35, background='gray35', foreground='snow')
self.input1.grid(row = 0, column = 1)
self.input2.grid(row = 1, column = 1)
self.close_button.grid(row = 2, column = 0)
self.add_button = tk.Button(master, text = "Add", command = self.add)
self.add_button.grid(row = 2, column = 1)
master.configure(background = 'grey')
return
#-------------------------------------------------
def add(self):
val = self.input1.get()
print(val)
#-------------------------------------------------
#-------------------------------------------------
root = Tk()
calc = Calculator(root)
root.mainloop()
This should now work how you wanted it too. The variables within the entry can be changed to suit. You were correct in calling the value of the entry with self.input1.get().
Hope this has helped.
I am trying to develop a class population counter. The problem is that when I run it 2 program come up. I wanted my program to be all in one. The counter keeps coming in a separate program and i can't transfer it into my actual program. How do I do this?
Here is my attached files, I am using Python
import pickle
import os.path
from tkinter import *
import tkinter.messagebox
import tkinter as tk
population = 0
def counter_label(label):
population = 0
def count():
global population
population +=1
label.config(text=str(population))
root = tk.Tk()
label = tk.Label(root)
label.pack()
counter_label(label)
button = tk.Button(root, text='Population Count', command=count).pack()
root.mainloop()
class Class:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
class ClassPopulation:
def __init__(self):
window = Tk()
window.title("Class population")
self.firstnameVar = StringVar()
self.lastnameVar = StringVar()
frame1 = Frame(window)
frame1.pack()
Label(frame1, text = "First name").grid(row = 1,
column = 1, sticky = W)
Entry(frame1, textvariable = self.firstnameVar,
width = 40).grid(row = 1, column = 2)
frame2 = Frame(window)
frame2.pack()
Label(frame2, text = "Last name").grid(row = 1, column = 1, sticky = W)
Entry(frame2, textvariable = self.lastnameVar,
width = 40).grid(row = 1, column = 2)
frame3 = Frame(window)
frame3.pack()
Button(frame3, text = "Add to classlist",
command = self.processAdd).grid(row = 1, column = 1)
frame4 = Frame(window)
frame4.pack()
Label(frame4, text = "Population Count").grid(row = 1, column = 1, sticky = W)
frame5 = Frame(window)
frame5.pack()
Label(frame5, text = "0").grid(row = 1, column = 1, sticky = W)
self.classList = self.loadClass()
self.current = 0
if len(self.classList) > 0:
self.setClass()
def saveClass(self):
outfile = open("Population.dat", "wb")
pickle.dump(self.classList, outfile)
tkinter.messagebox.showinfo("Class Population","New name registered")
outfile.close()
def loadClass(self):
if not os.path.isfile("Population.dat"):
return [] # Return an empty list
try:
infile = open("Population.dat", "rb")
classList = pickle.load(infile)
except EOFError:
classList = []
infile.close()
return classList
def processAdd(self):
classList = Class(self.firstnameVar.get(), self.lastnameVar.get())
self.classList.append(classList)
self.saveClass()
def setClass(self):
self.firstnameVar.set(self.classList[self.current].firstname)
self.lastnameVar.set(self.classList[self.current].lastname)
ClassPopulation()
I think two windows are coming up is because the program runs Tk() twice - one root = tk.Tk() and another in window = Tk(). If you pass your root Tkinter instance to the class ClassPopulation, then it should show one single window.
[EDIT]
class Class:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
class ClassPopulation:
def __init__(self, root_window):
window = self.root_window
window.title("Class population")
population = 0
def counter_label(label):
population = 0
def count():
global population
population +=1
label.config(text=str(population))
root = Tk()
label = tk.Label(root)
label.pack()
ClassPopulation( root )
counter_label(label)
root.mainloop()
I'm just beginning to program in python and I'm using it to make a little program with an GUI (using tkinter) that can take data from an excel file (using openpyxl). Let the user change things when necesarry and then use a button to write the data from the entries to a data file (.dat) (preferable by updating the values in the defaultdict arrays and then write the .dat file) and use a modelling language (pyomo) to create a model with the provided data and solve it with the cbc solver.
I'm now sofar that I made the model, the graphical interface (which is filled with data from the excel file). However I can't get the data in the entries fields back (to write update the defaultdicts arrays). I understand the simple examples on stackoverflow (with entry.get()), but it didn't worked on my example (probably because I use notbook tabs, panels and frames or I messed something up).
I use notebook tabs instead of one page, because I will have more (around 5) other categories of data in the complete program. At last I want to make the programm is such a way that it can adapt to the input (so it does not know if there are going to be 3, 8 or 10 facilities). I use python version 3.5.1. Here is the link to the excel file: 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()
And this is the class I made:
from tkinter import *
class FacilityPanel(Frame):
def __init__(self, app, facility_name, capacity, safetystock, maxpressure, compulsorystarttime, compulsoryendtime, demandma, demanddi, demandwo, demanddo, demandvr, demandza, demandzo):
Frame.__init__(self, app)
group = LabelFrame(self, text=facility_name)
group.pack(side =LEFT)
group.enable_facility = IntVar()
enable_button = Checkbutton(group, variable = group.enable_facility,
command = print("toggle"))
enable_button.pack(side = LEFT)
enable_button.select()
group.init_level = IntVar()
init_label = Label(group, text="Current Level: 5,06 m\u00B3")
init_label.pack(side = LEFT)
group.capacity = DoubleVar()
capacity_label = Label(group, text="Capacity:")
capacity_label.pack(side = LEFT)
capacity_entry = Entry(group, width=8)
capacity_entry.pack(side = LEFT)
capacity_entry.insert(0, capacity)
capacity_label_unit = Label(group, text="kg ")
capacity_label_unit.pack(side = LEFT)
group.safetystock = DoubleVar()
safetystock_label = Label(group, text="Safetystock:")
safetystock_label.pack(side = LEFT)
safetystock_entry = Entry(group, width=8)
safetystock_entry.pack(side = LEFT)
safetystock_entry.insert(0, safetystock)
safetystock_label_unit = Label(group, text="kg ")
safetystock_label_unit.pack(side = LEFT)
group.maxpressure = DoubleVar()
maxpressure_label = Label(group, text="Maxpressure:")
maxpressure_label.pack(side = LEFT)
maxpressure_entry = Entry(group, width=8)
maxpressure_entry.pack(side = LEFT)
maxpressure_entry.insert(0, maxpressure)
maxpressure_label_unit = Label(group, text="bar ")
maxpressure_label_unit.pack(side = LEFT)
group.comp_start_time = DoubleVar()
comp_time1_label = Label(group, text="Unload time window:")
comp_time1_label.pack(side = LEFT)
comp_start_time_entry = Entry(group, width=8)
comp_start_time_entry.pack(side = LEFT)
comp_start_time_entry.insert(0, compulsorystarttime)
comp_time2_label = Label(group, text="-")
comp_time2_label.pack(side = LEFT)
comp_end_time_entry = Entry(group, width=8)
comp_end_time_entry.pack(side = LEFT)
comp_end_time_entry.insert(0, compulsoryendtime)
comp_time3_label = Label(group, text="hours ")
comp_time3_label.pack(side = LEFT)
group.demandmaandag = DoubleVar()
demandmaandag_label = Label(group, text="Maandag:")
demandmaandag_label.pack(side = LEFT)
demandmaandag_entry = Entry(group, width=8)
demandmaandag_entry.pack(side = LEFT)
demandmaandag_entry.insert(0, demandma)
demandmaandag_label_unit = Label(group, text="kg ")
demandmaandag_label_unit.pack(side = LEFT)
group.demanddinsdag = DoubleVar()
demanddinsdag_label = Label(group, text="Dinsdag:")
demanddinsdag_label.pack(side = LEFT)
demanddinsdag_entry = Entry(group, width=8)
demanddinsdag_entry.pack(side = LEFT)
demanddinsdag_entry.insert(0, demanddi)
demanddinsdag_label_unit = Label(group, text="kg ")
demanddinsdag_label_unit.pack(side = LEFT)
group.demandwoensdag = DoubleVar()
demandwoensdag_label = Label(group, text="Woensdag:")
demandwoensdag_label.pack(side = LEFT)
demandwoensdag_entry = Entry(group, width=8)
demandwoensdag_entry.pack(side = LEFT)
demandwoensdag_entry.insert(0, demandwo)
demandwoensdag_label_unit = Label(group, text="kg ")
demandwoensdag_label_unit.pack(side = LEFT)
group.demanddonderdag = DoubleVar()
demanddonderdag_label = Label(group, text="Donderdag:")
demanddonderdag_label.pack(side = LEFT)
demanddonderdag_entry = Entry(group, width=8)
demanddonderdag_entry.pack(side = LEFT)
demanddonderdag_entry.insert(0, demanddo)
demanddonderdag_label_unit = Label(group, text="kg ")
demanddonderdag_label_unit.pack(side = LEFT)
group.demandvrijdag = DoubleVar()
demandvrijdag_label = Label(group, text="Vrijdag:")
demandvrijdag_label.pack(side = LEFT)
demandvrijdag_entry = Entry(group, width=8)
demandvrijdag_entry.pack(side = LEFT)
demandvrijdag_entry.insert(0, demandvr)
demandvrijdag_label_unit = Label(group, text="kg ")
demandvrijdag_label_unit.pack(side = LEFT)
group.demandzaterdag = DoubleVar()
demandzaterdag_label = Label(group, text="Zaterdag:")
demandzaterdag_label.pack(side = LEFT)
demandzaterdag_entry = Entry(group, width=8)
demandzaterdag_entry.pack(side = LEFT)
demandzaterdag_entry.insert(0, demandza)
demandzaterdag_label_unit = Label(group, text="kg ")
demandzaterdag_label_unit.pack(side = LEFT)
group.demandzaterdag = DoubleVar()
demandzondag_label = Label(group, text="Zondag:")
demandzondag_label.pack(side = LEFT)
demandzondag_entry = Entry(group, width=8)
demandzondag_entry.pack(side = LEFT)
demandzondag_entry.insert(0, demandzo)
demandzondag_label_unit = Label(group, text="kg ")
demandzondag_label_unit.pack(side = LEFT)
I found something that worked on this question:
tkinter create labels and entrys dynamically
I made a global entry for every entryfield