Binding one combobox to another combobox in while loop in tkinter - python

*I wanted to bind platform_id drop combobox to teh combobox_b so taht if cpu is selected in platform_id_drop, then cpu frequencies must be listed otherwise gpu frequencies must be listed. I am using while loop to create a number of rows based on input we are giving and used dictionary to store respective columns. I am able to get only fo rone set of row i.e frequencies are display oly for one row but not for other rows. Having Problem with bind function. Please help me with this.
'''
import pandas as pd
from tkinter import filedialog
from tkinter import ttk
from tkinter.filedialog import asksaveasfile
import collections
app=Tk()
app.title("trace")
app.geometry("1000x500")
global z
required=2
z=required
global global_id
global_id=0
global text_file_3
global text_file_4
a_dict = collections.defaultdict(list)
a_dict['global_id']={}
a_dict['unique_dag_id']={}
a_dict['platform_id']={}
a_dict['deadline']={}
a_dict['wcet_cpu']={}
a_dict['wcet_gpu']={}
a_dict['input_arrival_time']={}
a_dict['hyper_period_entry']={}
a_dict['input_task_period']={}
a_dict['frequency']={}
unique_dag_id = StringVar()
wcet_cpu = StringVar()
wcet_gpu = StringVar()
deadline = StringVar()
input_arrival_time = StringVar()
hyper_period_entry = StringVar()
input_task_period=StringVar()
frequency=StringVar()
last_county=StringVar()
v=[]
dict1={'gpu':['177000000' ,'266000000' ,'350000000' ,'420000000' ,'480000000', '543000000' , '600000000'],'cpu':['200000000', '300000000', '400000000', '500000000', '600000000', '700000000', '800000000', '900000000', '1000000000' ,'1100000000', '1200000000', '1300000000', '1400000000', '1500000000' ,'1600000000', '1700000000', '1800000000', '1900000000', '2000000000']}
def save_trace1():
global global_id
global_id_info=global_id_entry
if(platform_id_drop.get()=='cpu'):
platform_id_info=0
else:
platform_id_info=1
unique_dag_id_info=unique_dag_id_entry
wcet_cpu_info=wcet_cpu_entry.get()
wcet_gpu_info=wcet_gpu_entry.get()
deadline_info=deadline_entry.get()
input_arrival_time_info=input_arrival_time_entry.get()
hyper_period_entry_info=hyper_period_entry_entry.get()
input_task_period_info=input_task_period_entry.get()
combobox_b_info=combobox_b.get()
for i in range(required):
print(a_dict['platform_id'][i].get())
global_id_label=Label(text="global_id ")
platform_id_label=Label(text='platform_id')
unique_dag_id_label=Label(text='unique_dag-id')
wcet_cpu_label=Label(text='wcet_cpu')
wcet_gpu_label=Label(text='wcet_gpu')
deadline_label=Label(text='deadline')
input_arrival_time_label=Label(text='input-arrival time')
hyper_period_entry_label=Label(text='hyper_period_entry')
input_task_period_label=Label(text='input_task_period')
freq_label=Label(text='Frequency')
platform_id_options=[
'cpu','gpu',
]
global_id_label.place(x=50,y=50)
platform_id_label.place(x=150,y=50)
unique_dag_id_label.place(x=330,y=50)
wcet_cpu_label.place(x=450,y=50)
wcet_gpu_label.place(x=600,y=50)
deadline_label.place(x=750,y=50)
input_arrival_time_label.place(x=900,y=50)
hyper_period_entry_label.place(x=1050,y=50)
input_task_period_label.place(x=1200,y=50)
freq_label.place(x=1350,y=50)
trace_entries=[]
dag_entries=[]
while(z>0):
#platform_id_drop.pack(pady=20)
def selo(eventobj):
v=[]
if(platform_id_drop.get()=='cpu'):
print("a")
v=['200000000', '300000000', '400000000', '500000000', '600000000',
'700000000', '800000000', '900000000', '1000000000' ,'1100000000', '1200000000', '1300000000', '1400000000', '1500000000' ,'1600000000', '1700000000', '1800000000', '1900000000', '2000000000']
elif(platform_id_drop.get()=='gpu'):
print("m")
v=['177000000' ,'266000000' ,'350000000' ,'420000000' ,'480000000', '543000000' , '600000000']
global_id_entry=Label(text=str(global_id))
global_id_entry.place(x=50,y=50+60*(global_id+1))
a_dict['global_id'][global_id]=global_id
unique_dag_id_entry=Label(text=str(global_id))
unique_dag_id_entry.place(x=330,y=50+60*(global_id+1))
a_dict['unique_dag_id'][global_id]=unique_dag_id_entry
wcet_cpu_entry=Entry(app)
wcet_cpu_entry.place(x=450,y=50+60*(global_id+1))
a_dict['wcet_cpu'][global_id]=wcet_cpu_entry
wcet_gpu_entry=Entry(app)
wcet_gpu_entry.place(x=600,y=50+60*(global_id+1))
a_dict['wcet_gpu'][global_id]=wcet_gpu_entry
deadline_entry=Entry(app)
deadline_entry.place(x=750,y=50+60*(global_id+1))
a_dict['deadline'][global_id]=(deadline_entry)
input_arrival_time_entry=Entry(app)
input_arrival_time_entry.place(x=900,y=50+60*(global_id+1))
a_dict['input_arrival_time'][global_id]=(input_arrival_time_entry)
hyper_period_entry_entry=Entry(app)
hyper_period_entry_entry.place(x=1050,y=50+60*(global_id+1))
a_dict['hyper_period_entry'][global_id]=(hyper_period_entry_entry)
input_task_period_entry=Entry(app)
input_task_period_entry.place(x=1200,y=50+60*(global_id+1))
a_dict['input_task_period'][global_id]=( input_task_period_entry)
platform_id_drop=ttk.Combobox(app,values=platform_id_options)
platform_id_drop.bind("<<ComboboxSelected>>",selo)
platform_id_drop.place(x=150,y=50+60*(global_id+1))
a_dict['platform_id'][global_id]=platform_id_drop
combobox_b = ttk.Combobox(app,values=v)
combobox_b.place(x=1350,y=50+60*(global_id+1))
a_dict['frequency'][global_id]=( combobox_b )
v.clear()
global_id=global_id+1
z=z-1
button=Button(app,text="save_info",command=save_trace1)
button.place(x=0,y=0)
app.mainloop()
'''

Related

How to store a lot of data from a treeview in a list, Python

I have the following problem with this part of my code I explain
What this function does is get the data from the DB and then fill the Treeview
def obtenerDatos():
cursor = conexion.cursor()
cursor.execute("SELECT empresas.empresa, picos.pico, tamano_precio.tamano FROM cilindros, empresas, picos, tamano_precio WHERE empresa_id = empresas.id AND pico_id = picos.id AND tamano_id = tamano_precio.id AND jefesf_id =? ORDER BY cilindros.tamano_id ASC", (validarCi,))
datosConsulta = cursor.fetchall()
return datosConsulta
cursor.close()
cursor.execute("SELECT * FROM jefesf WHERE ci =?", (validarCi,))
Then I use an if to check if there are people with that data registered in the DB
if cursor.fetchall():
ventana3 = Toplevel()
datosConsulta = obtenerDatos()
contador = 0
datosJefes = ttk.Treeview(ventana3, columns=("colum1", "colum2"))
datosJefes.column("#0", width=80)
datosJefes.column("colum1", width=80, anchor=CENTER)
datosJefes.column("colum2", width=80, anchor=CENTER)
datosJefes.heading("#0", text="Empresa")
datosJefes.heading("colum1", text="Pico")
datosJefes.heading("colum2", text="Tamaño")
Here I begin to fill the Treview with the data
for listado in datosConsulta:
datosJefes.insert("", "end", text=listado[0], values=(listado[1], listado[2]))
datosJefes.pack()
This is where I have the problem, what I want to do is to be able to select records from the treview and that those records are saved in a multilist and print them to me by console, but I don't know how
def SeleccinarRegistro():
global listaCilin
global dato1
global dato2
listaCilin = []
dato = datosJefes.item(datosJefes.selection())
datos = list(dato.values())
dato1 = datos[0]
dato2 = datos[2][0]
dato3 = datos[2][1]
I tried with a While loop but it generates an infinite loop, and my idea was every time I press the button the loop runs and saves the elements in the list
while SeleccinarRegistro:
listaCilin.append([dato1, dato2, dato3, validarCi])
print("Empresa: ", dato1)
print("Pico: ", dato2)
print("Tamano: ", dato3)
print(listaCilin)
Button(ventana3, text="Seleccionar", command=SeleccinarRegistro).pack()

binding tkinter OptionsMenus by category

im struggling to bind tkinter options menus by category. ive made a simple to run version of the problem below. it seems to work at first. eg, in the image below you can see it succesfully categorizing by the name dave.
######## UPDATE
by passing a default value into my function i got it to work, now it only uses the default value. However, it always uses this default value. i assumed it would use the value i clicked on. but it always uses the default value.
from tkinter import *
data = {"names" :["dave" , "dave" , "dave" , "bob" , "sadie" , "jessica"] , "ages":[96,96,10,11,14,26] , "sexes":["m" , "f" , "m" , "m" , "f" , "f"]}
def age_selected_func(age_selected):
print("age selected " +str(age_selected))
sexes_object['menu'].delete(0, 'end')
good_sexes = []
for s, a in zip(data['sexes'], data['ages']):
if a == age_selected:
sexes_object['menu'].add_command(label=s, command=lambda s="none": sex_selected_func(s)) ## command=lambda a <- this is the problem it doesnt know what a is , but i need to pass a into it or its useless
ages_top_label_object.set(age_selected)
def name_selected_func(name_selected):
print("name selected")
ages_object['menu'].delete(0, 'end')
good_ages = []
for n, a in zip(data['names'], data['ages']):
if n == name_selected:
ages_object['menu'].add_command(label=a, command=lambda a="none": age_selected_func(a)) ## command=lambda a <- this is the problem it doesnt know what a is , but i need to pass a into it or its useless
names_top_label_object.set(name_selected)
window=Tk()
window.geometry("800x500+10+20")
names_top_label_object = StringVar(window)
names_top_label_object.set("choose a name")
names_object = OptionMenu(window, names_top_label_object, *data["names"] , command= lambda name_selected: name_selected_func(name_selected ))
names_object.pack();
names_object.place(x=25, y=100);
ages_top_label_object = StringVar(window)
ages_top_label_object.set("choose an age")
ages_object = OptionMenu(window, ages_top_label_object, *data["ages"] , command= lambda model_c: model_selected(model_c ))
ages_object.pack();
ages_object.place(x=25, y=150);
sexes_top_label_object = StringVar(window)
sexes_top_label_object.set("choose an sex")
sexes_object = OptionMenu(window, sexes_top_label_object , *data["sexes"] , command= lambda make_c: make_selected(make_c ))# , model_top_label_object, deriv_object , deriv_top_label_object ))
sexes_object.pack();
sexes_object.place(x=25, y=200);
how can i bind these 3 drop down boxes?

Problem with Messagebox it runs only that

i dont know why i cannot put all of my code
i created a function w3 and i add some checkbuttons the problem is that if the user clicks "< Υποβολή >" the function listokouti only recognizes the messagebox and its like i never put elif,can anyone help?
i1=IntVar()
i2=IntVar()
i3=IntVar()
i4=IntVar()
i5=IntVar()
#i6=IntVar()
#i7=IntVar()
# checkbuttons
check1 = tk.Checkbutton(rain,text="Τίτλος",font=('',13),variable=i1,onvalue=1,offvalue=0).pack(expand=1,anchor="nw")
check2 = tk.Checkbutton(rain,text="Tίτλος(Μετάφραση)",font=('',13),variable=i2,onvalue=1,offvalue=0).pack(expand=1,anchor="nw")
check3 = tk.Checkbutton(rain,text="Συγγραφέας",font=('',13),variable=i3,onvalue=1,offvalue=0).pack(expand=1,anchor="nw")
check4 = tk.Checkbutton(rain,text="Λέξεις κλειδιά",font=('',13),variable=i4,onvalue=1,offvalue=0).pack(expand=1,anchor="nw")
check5 = tk.Checkbutton(rain,text="Λέξεις κλειδιά(Μετάφραση)",font=('',13),variable=i5,onvalue=1,offvalue=0).pack(expand=1,anchor="nw")
def listokouti():
if i1.get()==0 and i2.get()==0 and i3.get()==0 and i4.get()==0 and i5.get()==0 :
vsause=messagebox.showwarning("team.33","Παρακαλώ επιλέξτε φίλτρα")
elif i1.get()==1 or i2.get()==1 or i3.get()==1 or i4.get()==1 or i5.get()==1 :
money=tk.Tk()
money.title("team.33")
money.iconbitmap('C:\Program Files (x86)\icon.ico')
# money.config(bg="#000000")
frame=tk.Frame(money)
scrollarw1=ttk.Scrollbar(frame,orient=VERTICAL)
my_listbox= tk.Listbox(frame,yscrollcommand=scrollarw1.set,width=50)
scrollarw1.config(command=my_listbox.yview)
scrollarw1.pack(side=RIGHT,fill= Y)
scrollarw2=ttk.Scrollbar(frame,orient=HORIZONTAL)
scrollarw2.config(command=my_listbox.xview)
scrollarw2.pack(side=BOTTOM,fill= X)
frame.pack()
my_listbox.pack(pady=20)
# to item einai akyro to evala mono gia na leitoyrgei to scrollbar
for item in range(1,101):
my_listbox.insert(END,item)
butt =tk.Button(money,text="< Υποβολή >",font=("",10,'bold'),command=ergasia).pack()
money.mainloop()
b1 = tk.Button(rain,text="< Υποβολή >",font=("",10,"bold"),command= listokouti).pack(expand=1)
rain.mainloop()
w3()

Python - application to search excel database column - Using tkinter Pandas

The application should search one of the column in an excel and and display corresponding column as a result but i am not able to get the values. I think i am not able to map the dictionary to the display tab using tkinter. Please help.
Below file is in outlook
Search (Input) Result (Output)
1 a
2 b
3 c
4 d
from tkinter import *
import tkinter.messagebox
import pandas as pd
root=Tk()
root.geometry('450x550')
root.title("Welcome")
root.configure(background="silver")
#Entry widget object
textin=StringVar()
**exlist = pd.read_excel('foo6.xls', index_col=0).to_dict('index')**
def clk():
entered = ent.get()
output.delete(0.0,END)
try:
textin = exlist[entered]
except:
textin = 'SORRY NO INFO \n AVAILABLE!!!!!!!!\n'
output.insert(0.0,textin)
def ex():
tkinter.messagebox.showinfo("Program",'Exit')
exit()
def exitt():
tkinter.messagebox.showinfo("Program",'Exit')
exit()
def me():
text='\n XYZ \n Piyushrkc \n Nice'
saveFile=open('text.txt','w')
saveFile.write(text)
print('This are the entries::',text)
def hel():
help(tkinter)
def cont():
tkinter.messagebox.showinfo("S/W Contributors",'\n Piyush ___Version 1.0___')
def clr():
textin.set(" ")
menu = Menu(root)
root.config(menu=menu)
subm = Menu(menu)
menu.add_cascade(label="File",menu=subm)
subm.add_command(label="Memo",command=me)
subm.add_command(label="Save")
subm.add_command(label="Save As")
subm.add_command(label="Print")
subm.add_command(label="Exit",command=ex)
subm1 = Menu(menu)
menu.add_cascade(label="Tools",menu=subm1)
subm1.add_command(label="Tkinter Help",command=hel)
subm2 = Menu(menu)
menu.add_cascade(label="About",menu=subm2)
subm2.add_command(label="Contributors",command=cont)
lab=Label(root,text='Name :',font=('none 20 bold'))
lab.grid(row=0,column=1,sticky=W)
ent=Entry(root,width=20,font=('none 18 bold'),textvar=textin,bg='white')
ent.grid(row=0,column=2,sticky=W)
but=Button(root,padx=2,pady=2,text='Submit',command=clk,bg='powder blue',font=('none 18 bold'))
but.place(x=100,y=90)
but4=Button(root,padx=2,pady=2,text='Clear',font=('none 18 bold'),bg='powder blue',command=clr)
but4.place(x=220,y=90)
output=Text(root,width=20,height=8,font=('Time 20 bold'),fg="black")
output.place(x=100,y=200)
labb=Label(root,text='Results',font=('non 18 bold'))
labb.place(x=0,y=180)
but1=Button(root,padx=2,pady=2,text='Exit',command=exitt,bg='powder blue',font=('none 18 bold'))
but1.place(x=200,y=470)
root.mainloop()

Tkinter Python 3 reuse table functionality to put all the header on the left and all the values on the right

I have this class that give me back a table with header and values under:
class table (Frame):
def __init__(self, parent,controller,pagina,search=None):
Frame.__init__(self, parent)
self.controller = controller
self.pagina=pagina
self.search=search
self.CreateUI()
self.LoadTable()
self.grid(sticky = (N,S,W,E))
def fix_result (query_result): #used to fix the query result in a good format for the table
header=[]
lines=[]
i=0
while i<len(query_result):
header.append(query_result[i][0])
lines.append(query_result[i][1:len(query_result[i])])
i+=1
return (header,lines)
def CreateUI(self):
tv = Treeview(self)
if self.pagina=='home': #declare the info needed for the home page
tv.heading("#0", text='ID')
tv.column("#0", anchor='center',width =(len('ID')+40))
tv['columns'] = ('Data Scadenza','Ultimo Pagamento','Nome','Cognome' ,'Telefono' ,'Cellulare' ,'Email')
elif self.pagina=='user_info': # declare the info needed for the user page
tv.heading("#0", text='ID')
tv.column("#0", anchor='center',width =(len('ID')+40))
tv['columns'] = ('Nome' ,'Cognome' ,'Nascita' ,'Codicefiscale' ,'Indirizzo' ,'Citta' ,'Provincia' ,'Telefono' ,'Cellulare' ,'Email')
i=0
while i<len (tv['columns']):
tv.heading(tv['columns'][i],text=tv['columns'][i])
################ establish the width of the column based
if tv['columns'][i]=='Data Nascita' or tv['columns'][i]=='Telefono' or tv['columns'][i]=='Cellulare' or tv['columns'][i]=='Costo Iscr.' or tv['columns'][i]=='Data Corso' or tv['columns'][i]=='Prezzo Corso':
tv.column(tv['columns'][i], anchor='center',width =(len(tv['columns'][i])+70))
else:
tv.column(tv['columns'][i], anchor='center',width =(len(tv['columns'][i])+160))
i+=1
tv.grid(sticky = (N,S,W,E))
self.treeview = tv
def LoadTable(self):
db=DB()
if self.pagina=='home': #####create data for the table in case that we are in the home page
month_ago= date.today() + relativedelta(months=-1)
month=str(month_ago)
self.db=DB()
a=self.db.db_query("select m.id, m.dataiscrizione, m.datapagamento, u.nome, u.cognome, u.telefono, u.cellulare, u.email from membership m join users u on m.id=u.id where m.stato='0' and m.dataiscrizione<'"+month.replace("-", "/")+"' order by m.id")
self.result=table.fix_result (a)
#a use to be a=[(Value0.1, Value0.2),(Value1.1, Value1.2),...]
#self.result use to be self.result=[(Value0.1,Value1.1,Value2.1),[(Value1.2, Value1.3),(Value2.2, Value2.3),(Value3.2, Value3.3)]]
elif self.pagina=='user_info' and self.search!=None: #####create data for the table in case that we are in the user page
a=db.db_query("select * from users where id='"+str(self.search)+"'")
self.result=table.fix_result (a)
i=0
while i<len(self.result[0]): #introduce values in the table
self.treeview.insert('', 'end', text=str(self.result[0][i]), values=(self.result[1][i]))
i+=1
I'd like to re-use this functionality when the self.pagina=='user_info'; in this moment is working but create a table of this form:
Header1 | Header2 | Header3 |.....
---------------------------- .....
Value0.1| Value0.2| Value0.3|.....
Value1.1| Value1.2| Value1.3|.....
What I want is that in case that self.pagina=='home', the table still in this way, but in case that self.pagina=='user_info' I know that we have just 1 set of Value so I'd like to have:
Header1| Value0.1
Header2| Value0.2
Header3| Value0.3
Header4| Value0.4
................
In both case I have a result like this one, but in the second one I have every time just one row and for this reason I wanted a vertical table!
I try different things with this code but I couldn't re-use the same functionality but I had to write a new one.... Is there some way just to invert the table?

Categories

Resources