change label values when an entry value is changed - python-2.7

My problem at the moment is I am trying to change a label(label 16) to the first value of entry_values[0] which isn't working I have tried passing it in as a variable and many other things, after about an hour of research I couldn't find a solution.I think the main problem is that it sets the label before the code with the entry is run so that it wont change. when I set it to a textvariable it produces an empty string (I think) but when I use just text it puts in a 0 where I expect my number.
def sub_menu(root):
global subpage
subpage = Frame(root)
button5 = Button(subpage, text="Save Generation Data",
command = lambda: save_entries())
button5.grid(row = 1, column = 6, sticky = E)
button6 = Button(subpage, text="Return To Main Page",
command = lambda: switch_page("main"))
button6.grid(row = 0, column = 6, sticky = W)
juveniles_label0 = Label(subpage,text="Juveniles")
adults_label1 = Label(subpage,text="Adults")
seniles_label2 = Label(subpage,text="Seniles")
population_label3 = Label(subpage,text="Population (Thousands)")
survival_rate_label4 = Label(subpage,text="Survival Rate (Between 0 and 1)")
birth_rate_label5 = Label(subpage,text="Birth Rate")
number_of_gens_label6 = Label(subpage,text="Number of Generations")
disease_trigger_label7 = Label(subpage,text="Disease Trigger Point")
global entry0
entry0 = Entry(subpage)
global entry1
entry1 = Entry(subpage)
global entry2
entry2 = Entry(subpage)
global entry3
entry3 = Entry(subpage)
global entry4
entry4 = Entry(subpage)
global entry5
entry5 = Entry(subpage)
global entry6
entry6 = Entry(subpage)
global entry7
entry7 = Entry(subpage)
global entry8
entry8 = Entry(subpage)
juveniles_label0.grid(row = 0, column = 1)
adults_label1.grid(row = 0, column = 2)
seniles_label2.grid(row = 0, column = 3)
population_label3.grid(row = 1, column = 0)
survival_rate_label4.grid(row = 2, column = 0)
birth_rate_label5.grid(row = 3, column = 0)
number_of_gens_label6.grid(row = 3, column = 2)
disease_trigger_label7.grid(row = 4, column = 0)
entry0.grid(row = 1, column = 1)
entry1.grid(row = 1, column = 2)
entry2.grid(row = 1, column = 3)
entry3.grid(row = 2, column = 1)
entry4.grid(row = 2, column = 2)
entry5.grid(row = 2, column = 3)
entry6.grid(row = 3, column = 1)
entry7.grid(row = 3, column = 3)
entry8.grid(row = 4, column = 1)
return subpage
def save_entries(): #entry recieve point
save_page = Frame(root)
""" if e0 < 0:
make a check to check if value is < 0 dont accept and if a value is inputed or not using if type(string_name) == str """
e0 = entry0.get()
if e0 >= 0:
entry_values[0] = (e0)
e1 = entry1.get()
if e0 >= 0:
entry_values[1] = (e1)
e2 = entry2.get()
if e0 >= 0:
entry_values[2] = (e2)
e3 = entry3.get()
if e0 >= 0:
entry_values[3] = (e3)
e4 = entry4.get()
if e0 >= 0:
entry_values[4] = (e4)
e5 = entry5.get()
if e0 >= 0:
entry_values[5] = (e5)
e6 = entry6.get()
if e0 >= 0:
entry_values[6] = (e6)
e7 = entry7.get()
if e0 >= 0:
entry_values[7] = (e7)
e8 = entry8.get()
if e0 >= 0:
entry_values[8] = (e8)
print entry_values
return save_page
def display_values(root):
sub2 = Frame(root)
global entry_values
label8 = Label(sub2, text = "Juveniles")
label9 = Label(sub2, text = "Adults")
label10 = Label(sub2, text = "Seniles")
label11 = Label(sub2, text = "Population(Thousands)")
label12 = Label(sub2, text = "Survival Rate(Between 1 and 0)")
label13 = Label(sub2, text = "Birth Rate")
label14 = Label(sub2, text = "Number of Generations")
label15 = Label(sub2, text = "Disase Trigger Point")
label16 = Label(sub2, text = entry_values[0])
label17 = Label(sub2, textvariable = entry_values[1])
label18 = Label(sub2, textvariable = "")
label19 = Label(sub2, textvariable = "")
label20 = Label(sub2, textvariable = "")
label21 = Label(sub2, textvariable = "")
label22 = Label(sub2, textvariable = "")
label23 = Label(sub2, textvariable = "")
label24 = Label(sub2, textvariable = "")
button7 = Button(sub2, text="Return To Main Page",
command = lambda: switch_page("main"))
label8.grid(row = 0, column = 1)
label9.grid(row = 0, column = 2)
label10.grid(row = 0, column = 3)
label11.grid(row = 1, column = 0)
label12.grid(row = 2, column = 0)
label13.grid(row = 3, column = 0)
label14.grid(row = 3, column = 3)
label15.grid(row = 4, column = 0)
label16.grid(row = 1, column = 1)
label17.grid(row = 1, column = 2)
label18.grid(row = 1, column = 3)
label19.grid(row = 2, column = 1)
label20.grid(row = 2, column = 2)
label21.grid(row = 2, column = 3)
label22.grid(row = 3, column = 1)
label23.grid(row = 3, column = 3)
label24.grid(row = 4, column = 1)
button7.grid(row = 0, column = 0)
return sub2

In order to change the text of a label you can do:
label["text"] = textVar
or
label.config(text=textVar)
So in your above code, when the entry changes, reconfigure the label using one of the above options.

Related

How do I optimize ORM queries for faster results?

I have 80k+ Entries in table Calendar. When I run either of the following 2 methods, the filter or get is taking too long to execute and due to which server is getting crashed after sometime and no new entries are getting added. I want to know if there are any more methods from which I can solve this issue.
Method 1:
date_list = []
d1 = date(2022, 5, 1)
d2 = date(2022, 6, 30)
delta = d2 - d1
for i in range(delta.days + 1):
date_list.append(d1 + timedelta(days=i))
profiles = Profile.objects.all()
for j in date_list:
for i in profiles:
try:
Calendar.objects.get(date=j,emp_id = i.emp_id)
except Calendar.DoesNotExist:
e = Calander()
e.team = i.emp_process
e.date = j
e.emp_name = i.emp_name
e.emp_id = i.emp_id
e.emp_desi = i.emp_desi
e.att_actual = "Unmarked"
e.save()
Method 2:
date_list = []
d1 = date(2022, 5, 1)
d2 = date(2022, 6, 30)
delta = d2 - d1
for i in range(delta.days + 1):
date_list.append(d1 + timedelta(days=i))
profiles = Profile.objects.all()
for j in date_list:
for i in profiles:
cal = Calander.objects.filter(date=j,emp_id = i.emp_id).count()
if cal < 1:
e = Calander()
e.team = i.emp_process
e.date = j
e.emp_name = i.emp_name
e.emp_id = i.emp_id
e.emp_desi = i.emp_desi
e.att_actual = "Unmarked"
e.save()
Try this:
date_list = []
d1 = date(2022, 5, 1)
d2 = date(2022, 6, 30)
delta = d2 - d1
for i in range(delta.days + 1):
date_list.append(d1 + timedelta(days=i))
for j in date_list:
profiles = Profile.objects.exclude(emp_id__in=Calendar.objects.filter(date=j).values('emp_id'))
calendars = []
for i in profiles:
e = Calendar()
e.team = i.emp_process
e.date = j
e.emp_name = i.emp_name
e.emp_id = i.emp_id
e.emp_desi = i.emp_desi
e.att_actual = "Unmarked"
calendars.append(e)
Calendar.objects.bulk_create(calendars)

Why I'm getting "TypeError: Failed to convert object of type <type 'dict'> to Tensor."?

I'm new to TF and ML.
Details about data: Features(x) - (70 x 70 x 70) tensor for each sample, y - a float for each sample.
TFRecords created with the following code:
def convert_to_tf_records():
def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def _float64_feature(value):
return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))
tfrecords_filename = 'A-100-h2-h2o.tfrecords'
writer = tf.python_io.TFRecordWriter(tfrecords_filename)
# Get data from db for now.
db = connect('results-60-70.db')
data = db.select(selection='Ti')
i = 0
for row in data:
desc = np.array(json.loads(row.descriptor), dtype=np.float32)
print(desc.shape)
be = float(row.binding_energy) * 23 # Convert to Kcal/mol ?
desc = desc.flatten()
desc = desc.tostring()
example = tf.train.Example(features=tf.train.Features(feature={'voxel_grid': _bytes_feature(desc), 'binding_energy': _float64_feature(be)}))
writer.write(example.SerializeToString())
i += 1
if i >= 10:
break
Input function:
def my_input_function(fname, perform_shuffle=False, repeat_count=None):
def _parse_elements(example):
features = tf.parse_single_example(example, features={'voxel_grid': tf.FixedLenFeature([], tf.string), 'binding_energy': tf.FixedLenFeature([], tf.float32)})
vg = tf.decode_raw(features['voxel_grid'], tf.float32)
vg = tf.reshape(vg, [70, 70, 70])
vg = tf.convert_to_tensor(vg, dtype=tf.float32)
vg = {'voxel_grid': vg}
e = tf.cast(features['binding_energy'], tf.float32)
return vg, e
def input_function():
dataset = tf.data.TFRecordDataset(fname).map(_parse_elements)
dataset = dataset.repeat(repeat_count)
dataset = dataset.batch(5)
dataset = dataset.prefetch(1)
if perform_shuffle:
dataset.shuffle(20)
iterator = dataset.make_one_shot_iterator()
batch_features, batch_labels = iterator.get_next()
return batch_features, batch_labels
return input_function
Model function:
def my_model_function(features, labels, mode):
if mode == tf.estimator.ModeKeys.PREDICT:
tf.logging.info("my_model_fn: PREDICT, {}".format(mode))
elif mode == tf.estimator.ModeKeys.EVAL:
tf.logging.info("my_model_fn: EVAL, {}".format(mode))
elif mode == tf.estimator.ModeKeys.TRAIN:
tf.logging.info("my_model_fn: TRAIN, {}".format(mode))
feature_columns = [tf.feature_column.numeric_column('voxel_grid', shape=(70, 70, 70), dtype=tf.float32)]
# Create the layer of input
input_layer = tf.feature_column.input_layer(features, feature_columns)
input_layer = tf.reshape(input_layer, [-1, 70, 70, 70, 1])
# Convolution layers
conv1 = tf.layers.conv3d(inputs=input_layer, strides=(2, 2, 2), filters=32, kernel_size=(7, 7, 7))
conv2 = tf.layers.conv3d(inputs=conv1, strides=(2, 2, 2), filters=32, kernel_size=(7, 7, 7))
pool3 = tf.layers.max_pooling3d(inputs=conv2, pool_size=[2, 2, 2], strides=2)
flat = tf.layers.flatten(pool3)
dense1 = tf.layers.dense(inputs=flat, units=10, activation=tf.nn.relu)
dense2 = tf.layers.dense(inputs=dense1, units=10, activation=tf.nn.relu)
output = tf.layers.dense(inputs=dense2, units=1)
predictions = {'binding_energy': output}
if mode == tf.estimator.ModeKeys.PREDICT:
return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)
# Calculate loss
loss = tf.losses.mean_squared_error(labels=labels, predictions=predictions)
if mode == tf.estimator.ModeKeys.TRAIN:
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
train_op = optimizer.minimize(loss=loss, global_step=tf.train.get_global_step())
return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)
# Add evaluation metrics
eval_metric_ops = {"mse": tf.metrics.mean_squared_error(labels=labels, predictions=predictions['binding_energy'])}
if mode == tf.estimator.ModeKeys.EVAL:
return tf.estimator.EstimatorSpec(mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)
When calling model.train using
model = tf.estimator.Estimator(model_fn=my_model_function, model_dir='./model_dir')
model.train(input_fn=my_input_function('A-100-h2-h2o.tfrecords'), steps=100)
I get the following error.
TypeError: Failed to convert object of type to Tensor.
Found it!
changing
# Calculate loss
loss = tf.losses.mean_squared_error(labels=labels, predictions=predictions)
to
# Calculate loss
loss = tf.losses.mean_squared_error(labels=labels, predictions=predictions['binding_energy'])
solves the issue.

python tkinter how to organize the rows and columns

Hi I'm trying to build a user interface and having problem with column and row positions. What I expect to see is some distance between buttons and entry widgets since I left two empty column between them. So why are they standing just next to the entry widgets and changing the distances between entry areas? Could anyone give me some help about this?
Here is the code...
from Tkinter import*
HMCC=Tk()
HMCC.title(" GUI v1.0 ")
HMCC.geometry("500x300")
entry_1 = Entry(HMCC)
entry_2 = Entry(HMCC)
entry_3 = Entry(HMCC)
entry_4 = Entry(HMCC)
entry_5 = Entry(HMCC)
entry_6 = Entry(HMCC)
entry_7 = Entry(HMCC)
entry_8 = Entry(HMCC)
entry_1.grid(row=2,column=1)
entry_2.grid(row=3,column=1)
entry_3.grid(row=4,column=1)
entry_4.grid(row=5,column=1)
entry_5.grid(row=6,column=1)
entry_6.grid(row=7,column=1)
entry_7.grid(row=8,column=1)
entry_8.grid(row=9,column=1)
Channel_1 = Label(HMCC, text = "Channel 1 : ")
Channel_2 = Label(HMCC, text = "Channel 2 : ")
Channel_3 = Label(HMCC, text = "Channel 3 : ")
Channel_4 = Label(HMCC, text = "Channel 4 : ")
Channel_5 = Label(HMCC, text = "Channel 5 : ")
Channel_6 = Label(HMCC, text = "Channel 6 : ")
Channel_7 = Label(HMCC, text = "Channel 7 : ")
Channel_8 = Label(HMCC, text = "Channel 8 : ")
Channel_1.grid( row = 2, column = 0, sticky = E)
Channel_2.grid( row = 3, column = 0, sticky = E)
Channel_3.grid( row = 4, column = 0, sticky = E)
Channel_4.grid( row = 5, column = 0, sticky = E)
Channel_5.grid( row = 6, column = 0, sticky = E)
Channel_6.grid( row = 7, column = 0, sticky = E)
Channel_7.grid( row = 8, column = 0, sticky = E)
Channel_8.grid( row = 9, column = 0, sticky = E)
#button1 = Button(text=" START " , fg="red" )
#button2 = Button(text=" PAUSE " , fg="blue" )
#button3 = Button(text=" STOP ", fg="green")
#button4 = Button(text="QUIT" , fg="black",command=HMCC.quit)
#button1.grid( row = 1, column = 3)
#button2.grid( row = 2, column = 3)
#button3.grid( row = 3, column = 3)
#button4.grid( row = 4, column = 3)
HMCC.mainloop()
Current view
Thanks in advance
If there is nothing in column 2, then tkinter will ignore it.
In addition to the comment posted above which contains the answer to your question, you can clean up your code significantly by just using a loop:
num_rows = 8
entries = [None]*num_rows
channels = [None]*num_rows
for i in range(num_rows):
channels[i] = Label(HMCC, text = "Channel {0} : ".format(i+1))
channels[i].grid(row=i+2,column=0,sticky=E)
entries[i] = Entry(HMCC)
entries[i].grid(row=i+2, column=1)
Better yet, use list comprehension:
num_rows = 8
entries = [Entry(HMCC).grid(row=i+2, column=1) for i in range(num_rows)]
channels = [Label(HMCC, text = "Channel {0} : ".format(i)).grid(row=i+2,column=0,sticky=E) for i in range(num_rows)]

How to delete entire row in Tkinter grid layout

I am trying a test application with Tkinter. I have created a table using grid layout manager as shown below. There are two buttons - Add row and Delete row. Add row works as expected. How i can go about deleting selected rows. My idea was to give a Checkbutton for each row as shown below. And every selected row can be deleted. But i don't know how to do it exactly and if its possible.
Is there a better way to delete the rows in this case ? please suggest a solution.
CODE:
from Tkinter import *
import ttk
from ttk import *
i =2
def add_row():
global i
var = IntVar()
c = Checkbutton(root, variable = var)
c.grid(row = i, column = 0)
for j in range(1,5): #Columns
b = Entry(root)
b.grid(row=i, column=j)
i =i+1
root = Tk()
bt = ttk.Button(root , text = 'Add Row', command = add_row)
bt.grid(row =0, column=0)
dl = ttk.Button(root , text = 'Delete Row')
dl.grid(row =0, column=1)
v0 = StringVar()
e0 = Entry(root, textvariable = v0, state = 'readonly')
v0.set('Select')
e0.grid(row = 1, column = 0 )
v1 = StringVar()
e1 = Entry(root, textvariable = v1, state = 'readonly')
v1.set('Col1')
e1.grid(row = 1, column = 1 )
v2 = StringVar()
e2 = Entry(root, textvariable = v2, state = 'readonly')
v2.set('Col2')
e2.grid(row = 1, column = 2)
v3 = StringVar()
e3 = Entry(root, textvariable = v3, state = 'readonly')
v3.set('Col3')
e3.grid(row = 1, column = 3 )
v4 = StringVar()
e4 = Entry(root, textvariable = v4, state = 'readonly')
v4.set('Col4')
e4.grid(row = 1, column = 4 )
mainloop()
Note: I do not want to use tktable or treeview to create tables.
In order to delete widgets, you need to keep a reference to them when they are created.
In the code below, I have created a list rows which has a sub-list items for each row. Each row contains a reference to the checkbutton and all the entries.
When Delete Row is pressed, the function loops through the list and destroys all items in the row that has the checkbutton activated, then removes the entry from the list.
Notes:
I have made var an attribute of the checkbutton, so that we can access it to see if it has been checked - see this question.
You were creating your checkbutton five times for each row; I've taken it out of the loop.
I iterate through the list of rows backwards, so that when an item is pop-ed, it only changes the index for the rows already processed. This means that you can delete multiple rows at once.
from Tkinter import *
import ttk
from ttk import *
i=2
rows = []
def add_row():
global i
i=i+1
items = []
var = IntVar()
c = Checkbutton(root, variable = var)
c.val = var
items.append(c)
c.grid(row = i, column = 0)
for j in range(1,5): #Columns
b = Entry(root)
items.append(b)
b.grid(row=i, column=j)
rows.append(items)
def delete_row():
for rowno, row in reversed(list(enumerate(rows))):
if row[0].val.get() == 1:
for i in row:
i.destroy()
rows.pop(rowno)
root = Tk()
bt = ttk.Button(root , text = 'Add Row', command = add_row)
bt.grid(row =0, column=0)
dl = ttk.Button(root , text = 'Delete Row', command = delete_row)
dl.grid(row =0, column=1)
v0 = StringVar()
e0 = Entry(root, textvariable = v0, state = 'readonly')
v0.set('Select')
e0.grid(row = 1, column = 0 )
v1 = StringVar()
e1 = Entry(root, textvariable = v1, state = 'readonly')
v1.set('Col1')
e1.grid(row = 1, column = 1 )
v2 = StringVar()
e2 = Entry(root, textvariable = v2, state = 'readonly')
v2.set('Col2')
e2.grid(row = 1, column = 2)
v3 = StringVar()
e3 = Entry(root, textvariable = v3, state = 'readonly')
v3.set('Col3')
e3.grid(row = 1, column = 3 )
v4 = StringVar()
e4 = Entry(root, textvariable = v4, state = 'readonly')
v4.set('Col4')
e4.grid(row = 1, column = 4 )
mainloop()

Getting selected items from a Tkinter listbox without using a listbox bind

I have 2 listboxes (which are connected so that items can move from one to the other) and at the end I would like to get all the entries in the second listbox by using a 'Ok' button (or simply closing the frame). I could add/remove values to a list every time an item is selected (as shown in the commented section of the code below) but I would rather have a single line of code along the lines of [master.selected.get(idx) for idx in master.selected.curselection()] in the close function but I am unable to get it working.
Code:
def measurementPopup(self,master):
self.chargeCarrier = StringVar()
self.massModifiers = StringVar()
self.chargeCarrier.set("[M+xH]")
def onselect1(evt):
w = evt.widget
index = int(w.curselection()[0])
value = w.get(index)
# My Dirty fix -> Here I could enter the selected value to a buffer list (to be returned in the ok function).
master.selected.insert(END,value)
master.avail.delete(index)
def onselect2(evt):
w = evt.widget
index = int(w.curselection()[0])
value = w.get(index)
# My Dirty fix -> Here I could remove the selected value from a buffer list (to be returned in the ok function).
master.selected.delete(index)
master.avail.insert(END,value)
def close(self):
# Here I would return the buffer list and close the window
master.measurementWindow = 0
top.destroy()
if master.measurementWindow == 1:
return
master.measurementWindow = 1
top = self.top = Toplevel()
top.protocol( "WM_DELETE_WINDOW", lambda: close(self))
self.charge = Label(top, text = "Charge", width = 10)
self.charge.grid(row = 0, column = 0, sticky = W)
self.min = Label(top, text = "Min", width = 5)
self.min.grid(row=0, column = 1, sticky = W)
self.minCharge = Spinbox(top, from_= 1, to = 3, width = 5)
self.minCharge.grid(row = 0, column = 2, sticky = W)
self.max = Label(top, text = "Max", width = 5)
self.max.grid(row = 0, column = 3, sticky = W)
self.maxCharge = Spinbox(top, from_ = 1, to=3, width=5)
self.maxCharge.grid(row = 0, column = 4, sticky = W)
self.chargeCarrier = OptionMenu(top, self.chargeCarrier, "[M+xH]", "[M+xNa]")
self.chargeCarrier.grid(row = 0, column = 5, sticky = W)
self.availMass = Label(top, text = "Available")
self.availMass.grid(row = 1, column = 1, sticky = W)
self.selectMass = Label(top, text = "Selected")
self.selectMass.grid(row = 1, column = 3, sticky = W)
self.massMod = Label(top, text = "Mass Mods")
self.massMod.grid(row = 2, column = 0, sticky = W)
self.avail = Listbox(top)
for i in UNITS:
if BLOCKS[i]['available'] == 1:
self.avail.insert(END,BLOCKS[i]['human_readable_name'])
self.avail.grid(row = 2, column = 1, columnspan = 2, sticky = W)
self.avail.bind('<<ListboxSelect>>',onselect1)
self.selected = Listbox(top)
self.selected.grid(row = 2, column = 3, columnspan = 2, sticky = W)
self.selected.bind('<<ListboxSelect>>',onselect2)
self.ok = Button(top,text = 'Ok',command = lambda: close(self))
self.ok.grid(row = 3, column = 0, sticky = W)
I have tried to use the following small snippet in the close function:
values = [master.selected.get(idx) for idx in master.selected.curselection()]
print ', '.join(values)
However, the for segment doesn't return anything. I would expect that this is due to the fact that nothing is actually selected but that I would need something opposite, along the lines of master.selected.allitems() (if it exists and if I understand it correctly).
Summary
How would one get all the items in 1 specific listbox?
The .get() function for the Listbox widget allows you to specify a range of items, which can be specified as 0 to END to return a tuple of all the items.
Example:
from Tkinter import *
root = Tk()
l = Listbox(root, width = 15)
l.pack()
l.insert(END, "Hello")
l.insert(END, "world")
l.insert(END, "here")
l.insert(END, "is")
l.insert(END, "an")
l.insert(END, "example")
def close():
global l, root
items = l.get(0, END)
print(items)
root.destroy()
b = Button(root, text = "OK", command = close).pack()
root.mainloop()
I hope this helps, if it's not what you were looking for let me know in a comment and I can try expand my answer.