I've run into an issue with the TabularAdapter in the TraitsUI package...
I've been trying to figure this out on my own for much too long now, so I wanted to ask the experts here for some friendly advise :)
I'm going to add a piece of my program that illustrates my problem(s), and I'm hoping someone can look it over and say 'Ah Ha!...Here's your problem' (my fingers are crossed).
Basically, I can use the TabularAdapter to produce a table editor into an array of dtypes, and it works just fine except:
1) whenever I change the # of elements (identified as 'Number of fractures:'), the array gets resized, but the table doesn't reflect the change until after I click on one of the elements. What I'd like to happen is that the # of rows (fractures) changes after I release the # of fractures slider. Is this doable?
2) The second issue I have is that if the array gets resized before it's displayed by .configure_traits() (by the notifier when Number_of_fractures gets modified), I can shrink the size of the array, but I can't increase it over the new size.
2b) I thought I'd found a way to have the table editor display the full array even when it's increased over the 5 set in the code (just before calling .trait_configure()), but I was fooled :( I tried adding another Group() in front of the vertical_fracture_group so the table wasn't the first thing to display. This more closely emulates my entire program. When I did this, I was locked into the new smaller size of the array, and I could no longer increase its size to my maximum of 15. I'm modifying the code to reflect this issue.
Here's my sample code:
# -*- coding: utf-8 -*-
"""
This is a first shot at developing a ****** User Interface using Canopy by
Enthought. Canopy is a distribution of the Python language which has a lot of
scientific and engineering features 'built-in'.
"""
#-- Imports --------------------------------------------------------------------
from traitsui.api import TabularEditor
from traitsui.tabular_adapter import TabularAdapter
from numpy import zeros, dtype
from traits.api import HasTraits, Range
from traitsui.api import View, Group, Item
#-- FileDialogDemo Class -------------------------------------------------------
max_cracks = 15 #maximum number of Fracs/cracks to allow
class VertFractureAdapter(TabularAdapter):
columns = [('Frac #',0), ('X Cen',1), ('Y Cen',2), ('Z Cen',3),
('Horiz',4), ('Vert',5), ('Angle',6)]
class SetupDialog ( HasTraits ):
Number_Of_Fractures = Range(1, max_cracks) # line 277
vertical_frac_dtype = dtype([('Fracture', 'int'), ('x', 'float'), ('y', 'float'),
('z', 'float'), ('Horiz Length', 'float'), ('Vert Length', 'float')
, ('z-axis Rotation, degrees', 'float')])
vertical_frac_array = zeros((max_cracks), dtype=vertical_frac_dtype)
vertical_fracture_group = Group(
Item(name = 'vertical_frac_array',
show_label = False,
editor = TabularEditor(adapter = VertFractureAdapter()),
width = 0.5,
height = 0.5,
)
)
#-- THIS is the actual 'View' that gets put on the screen
view = View(
#Note: When as this group 'displays' before the one with the Table, I'm 'locked' into my new maximum table display size of 8 (not my original/desired maximum of 15)
Group(
Item( name = 'Number_Of_Fractures'),
),
#Note: If I place this Group() first, my table is free to grow to it's maximum of 15
Group(
Item( name = 'Number_Of_Fractures'),
vertical_fracture_group,
),
width = 0.60,
height = 0.50,
title = '****** Setup',
resizable=True,
)
#-- Traits Event Handlers --------------------------------------------------
def _Number_Of_Fractures_changed(self):
""" Handles resizing arrays if/when the number of Fractures is changed"""
print "I've changed the # of Fractures to " + repr(self.Number_Of_Fractures)
#if not self.user_StartingUp:
self.vertical_frac_array.resize(self.Number_Of_Fractures, refcheck=False)
for crk in range(self.Number_Of_Fractures):
self.vertical_frac_array[crk]['Fracture'] = crk+1
self.vertical_frac_array[crk]['x'] = crk
self.vertical_frac_array[crk]['y'] = crk
self.vertical_frac_array[crk]['z'] = crk
# Run the program (if invoked from the command line):
if __name__ == '__main__':
# Create the dialog:
fileDialog = SetupDialog()
fileDialog.configure_traits()
fileDialog.Number_Of_Fractures = 8
In my discussion with Chris below, he made some suggestions that so far haven't worked for me :( Following is my 'current' version of this test code so Chris (or anyone else who wishes to chime in) can see if I'm making some glaring error.
# -*- coding: utf-8 -*-
"""
This is a first shot at developing a ****** User Interface using Canopy by
Enthought. Canopy is a distribution of the Python language which has a lot of
scientific and engineering features 'built-in'.
"""
#-- Imports --------------------------------------------------------------------
from traitsui.api import TabularEditor
from traitsui.tabular_adapter import TabularAdapter
from numpy import zeros, dtype
from traits.api import HasTraits, Range, Array, List
from traitsui.api import View, Group, Item
#-- FileDialogDemo Class -------------------------------------------------------
max_cracks = 15 #maximum number of Fracs/cracks to allow
class VertFractureAdapter(TabularAdapter):
columns = [('Frac #',0), ('X Cen',1), ('Y Cen',2), ('Z Cen',3),
('Horiz',4), ('Vert',5), ('Angle',6)]
even_bg_color = 0xf4f4f4 # very light gray
class SetupDialog ( HasTraits ):
Number_Of_Fractures = Range(1, max_cracks) # line 277
dummy = Range(1, max_cracks)
vertical_frac_dtype = dtype([('Fracture', 'int'), ('x', 'float'), ('y', 'float'),
('z', 'float'), ('Horiz Length', 'float'), ('Vert Length', 'float')
, ('z-axis Rotation, degrees', 'float')])
vertical_frac_array = Array(dtype=vertical_frac_dtype)
vertical_fracture_group = Group(
Item(name = 'vertical_frac_array',
show_label = False,
editor = TabularEditor(adapter = VertFractureAdapter()),
width = 0.5,
height = 0.5,
)
)
#-- THIS is the actual 'View' that gets put on the screen
view = View(
Group(
Item( name = 'dummy'),
),
Group(
Item( name = 'Number_Of_Fractures'),
vertical_fracture_group,
),
width = 0.60,
height = 0.50,
title = '****** Setup',
resizable=True,
)
#-- Traits Event Handlers --------------------------------------------------
def _Number_Of_Fractures_changed(self, old, new):
""" Handles resizing arrays if/when the number of Fractures is changed"""
print "I've changed the # of Fractures to " + repr(self.Number_Of_Fractures)
vfa = self.vertical_frac_array
vfa.resize(self.Number_Of_Fractures, refcheck=False)
for crk in range(self.Number_Of_Fractures):
vfa[crk]['Fracture'] = crk+1
vfa[crk]['x'] = crk
vfa[crk]['y'] = crk
vfa[crk]['z'] = crk
self.vertical_frac_array = vfa
# Run the program (if invoked from the command line):
if __name__ == '__main__':
# Create the dialog:
fileDialog = SetupDialog()
# put the actual dialog up...if I put it up 'first' and then resize the array, I seem to get my full range back :)
fileDialog.configure_traits()
#fileDialog.Number_Of_Fractures = 8
There are two details of the code that are causing the problems you describe. First, vertical_frac_array is not a trait, so the tabular editor cannot monitor it for changes. Hence, the table only refreshes when you manually interact with it. Second, traits does not monitor the contents of an array for changes, but rather the identity of the array. So, resizing and assigning values into the array will not be detected.
One way to fix this is to first make vertical_frac_array and Array trait. E.g. vertical_frac_array = Array(dtype=vertical_frac_dtype). Then, inside of _Number_Of_Fractures_changed, do not resize the vertical_frac_array and modify it in-place. Instead, copy vertical_frac_array, resize it, modify the contents, and then reassign the manipulated copy back to vertical_frac_array. This way the table will see that the identity of the array has changed and will refresh the view.
Another option is to make vertical_frac_array a List instead of an Array. This avoids the copy-and-reassign trick above because traits does monitor the content of lists.
Edit
My solution is below. Instead of resizing the vertical_frac_array whenever Number_Of_Fractures changes, I instead recreate the array. I also provide a default value for vertical_frac_array via the _vertical_frac_array_default method. (I removed from unnecessary code in the view as well.)
# -*- coding: utf-8 -*-
"""
This is a first shot at developing a ****** User Interface using Canopy by
Enthought. Canopy is a distribution of the Python language which has a lot of
scientific and engineering features 'built-in'.
"""
#-- Imports --------------------------------------------------------------------
from traitsui.api import TabularEditor
from traitsui.tabular_adapter import TabularAdapter
from numpy import dtype, zeros
from traits.api import HasTraits, Range, Array
from traitsui.api import View, Item
#-- FileDialogDemo Class -------------------------------------------------------
max_cracks = 15 #maximum number of Fracs/cracks to allow
vertical_frac_dtype = dtype([('Fracture', 'int'), ('x', 'float'), ('y', 'float'),
('z', 'float'), ('Horiz Length', 'float'), ('Vert Length', 'float')
, ('z-axis Rotation, degrees', 'float')])
class VertFractureAdapter(TabularAdapter):
columns = [('Frac #',0), ('X Cen',1), ('Y Cen',2), ('Z Cen',3),
('Horiz',4), ('Vert',5), ('Angle',6)]
class SetupDialog ( HasTraits ):
Number_Of_Fractures = Range(1, max_cracks) # line 277
vertical_frac_array = Array(dtype=vertical_frac_dtype)
view = View(
Item('Number_Of_Fractures'),
Item(
'vertical_frac_array',
show_label=False,
editor=TabularEditor(
adapter=VertFractureAdapter(),
),
width=0.5,
height=0.5,
),
width=0.60,
height=0.50,
title='****** Setup',
resizable=True,
)
#-- Traits Defaults -------------------------------------------------------
def _vertical_frac_array_default(self):
""" Creates the default value of the `vertical_frac_array`. """
return self._calculate_frac_array()
#-- Traits Event Handlers -------------------------------------------------
def _Number_Of_Fractures_changed(self):
""" Update `vertical_frac_array` when `Number_Of_Fractures` changes """
print "I've changed the # of Fractures to " + repr(self.Number_Of_Fractures)
#if not self.user_StartingUp:
self.vertical_frac_array = self._calculate_frac_array()
#-- Private Interface -----------------------------------------------------
def _calculate_frac_array(self):
arr = zeros(self.Number_Of_Fractures, dtype=vertical_frac_dtype)
for crk in range(self.Number_Of_Fractures):
arr[crk]['Fracture'] = crk+1
arr[crk]['x'] = crk
arr[crk]['y'] = crk
arr[crk]['z'] = crk
return arr
# Run the program (if invoked from the command line):
if __name__ == '__main__':
# Create the dialog:
fileDialog = SetupDialog()
fileDialog.configure_traits()
Related
I am working on the project the application is working fine
but small issue with list box,
I created a class where we can call get suggestion from the entry data a sample code is given below
from tkinter import *
root = Tk()
root.geometry('300x300')
search = StringVar()
search1 = StringVar()
search_list = ["Apple", "Ball", "cat", "dog"]
Label(root, text="Search :").pack(pady=15)
search1_ent = Entry(root, textvariable=search)
search1_ent.pack(pady=15)
search2_ent = Entry(root, textvariable=search1)
search2_ent.pack(pady=15)
list_box = Listbox(root, height=10, width=20)
EntryList.EntryBoxListLink(search_list, list_box, search1_ent, search, 90, 87, 20)
root.mainloop()
I created a py file on the name Entry list in that created a class Entry box list link,
It may not be perfect code but worked fine.
the class code is
import contextlib
from tkinter import *
class EntryBoxListLink:
"""this class is created to link entry box and the listbox"""
def __init__(self, list_data='', list_box='', entry_box=None, set_variable='', x_axis=38, y_axis=52, width=20,
next_entry=None):
self.list_data = list_data
self.list_box = list_box
self.entry_box = entry_box
self.set_variable = set_variable
self.x_axis = x_axis
self.y_axis = y_axis
self.width = width
def destroyListBox(event):
"""this is the command when the list box to place forget"""
with contextlib.suppress(BaseException):
self.list_box.place_forget()
def searchIList(event):
"""this gives the list box where the data no are aligned"""
self.list_box.config(width=self.width)
self.list_box.place(x=self.x_axis, y=self.y_axis)
self.list_box.bind('<Leave>', destroyListBox)
self.list_box.bind('<Double-1>', itemsSelected)
self.list_box.bind('<Return>', itemsSelected)
if self.list_data is not None:
match = [i for i in self.list_data if
(self.set_variable.get().lower() or self.set_variable.get().capitalize()) in i]
self.list_box.delete(0, END)
for c in match:
try:
self.list_box.insert(END, c.title())
except BaseException:
self.list_box.insert(END, c)
if not match:
destroyListBox(None)
if self.set_variable.get() == "":
destroyListBox(None)
def itemsSelected(event):
"""when the no is selected from list box it aligned to
the phone number and gives the data"""
for i in self.list_box.curselection():
self.set_variable.set(self.list_box.get(i))
self.entry_box.focus_set()
destroyListBox(None)
if next_entry is not None:
next_entry.focus()
def set_entry_focus(event):
if list_box.curselection()[0] == 0:
return self.entry_box.focus_set()
def focusAndSelect():
self.list_box.focus_set()
self.list_box.select_set(0)
self.entry_box.bind("<KeyRelease>", searchIList)
self.entry_box.bind("<Down>", lambda event: focusAndSelect())
self.list_box.bind("<Up>", set_entry_focus)
the issue is when I select the second entry box the list box should be gone,
to be more frank when the search1 and listbox are not in focus the list box should be place forget!
So I'm trying to determine what or how can I determine particular state of StyleOption. I used the '==' operator but building a QPushbutton it seems like it returns sometimes True and sometimes False for a particular metric.
Main.py
import sys
from PySide6.QtCore import *
from PySide6.QtWidgets import *
from CustomStyle import MyStyles
# Subclass QMainWindow to customize your application's main window
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Widgets App")
layout = QVBoxLayout()
# button
mPushBtn = QPushButton('click')
mPushBtn.setFlat(True)
layout.addWidget(mPushBtn)
widget = QWidget()
widget.setLayout(layout)
# Set the central widget of the Window. Widget will expand
# to take up all the space in the window by default.
self.setCentralWidget(widget)
app = QApplication(sys.argv)
app.setStyle(MyStyles('QPushButton'))
window = MainWindow()
window.show()
app.exec()
CustomStyle.py
from typing import Optional, Union
from PySide6.QtCore import *
from PySide6.QtGui import *
from PySide6.QtWidgets import *
from PySide6.QtCharts import *
class MyStyles(QCommonStyle):
def __init__(self, which_widget: str) -> None:
super().__init__(which_widget)
self.widget_name = which_widget
self.setObjectName('fpStyles')
def pixelMetric(self, m: QStyle.PixelMetric, opt: Optional[QStyleOption], widget: Optional[QWidget]) -> int:
if widget.__class__.__name__ == self.widget_name:
print(f'PixelMetric: metric > {m.name.decode()} -- styleOption > {opt.__class__.__name__} -- widget > {widget.__class__.__name__}')
if opt is not None: print(f'\tsize >>> {opt.rect.getRect()}')
if opt is not None: print(f'{opt.state == QStyle.State_Enabled}')
return super().pixelMetric(m, opt, widget)
Running the above produces following output
The QStyle State enum is a flag:
It stores an OR combination of StateFlag values.
This means that you cannot use the equality comparison, because using == will return True only if the state is exactly State_Enabled.
The correct operator is &, which will mask the bits that are equal to the given value, and that can be converted to a bool to check its truthfulness:
print(f'{bool(opt.state & QStyle.State_Enabled)}')
To clarify, State_Enable corresponds to 1 (both binary and integer, obviously), but if the state also contains another flag such as State_Raised (which is 2, or binary 10), state will be 3, or binary 11.
3 == 1 obviously returns False, but 3 & 1 masks the rightmost bit of 3, resulting in 1, and bool(1) results True.
Read more about bitwise operators.
Be aware that QCommonStyle is the basis for a completely new style. You should normally use QProxyStyle.
Note: assuming your imports are done consistently, it's usually better to use isinstance(obj, cls) instead of comparing the class name.
I would like to add information to my current dataset. At the moment, I have six-frame sequences in folders. The DataLoader reads all 6 and uses the first 3 for predicting the last 1/2/3 (depending on how many I tell him to). This is the function for the DataLoader.
class TrainFeeder(Dataset):
def init(self, data_set):
super(TrainFeeder, self).init()
self.input_data = data_set
#print(torch.cuda.current_device())
if torch.cuda.current_device() ==0:
print('There are total %d sequences in trainset' % len(self.input_data))
def getitem(self, index):
path = self.input_data[index]
imgs_path = sorted(glob.glob(path + '/*.png'))
imgs = []
for img_path in imgs_path:
img = cv2.imread(img_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = cv2.resize(img, (256,448))
img = cv2.resize(img, (0, 0), fx=0.5, fy=0.5, interpolation=cv2.INTER_CUBIC) #has been 0.5 for official data, new is fx = 2.63 and fy = 2.84
img_tensor = ToTensor()(img).float()
imgs.append(img_tensor)
imgs = torch.stack(imgs, dim=0)
return imgs
def len(self):
return len(self.input_data)
Now I'd like to add one value to these images. It is a boolean, I have stored in a list in a .json in the same folder, like the six-frame-sequences. But I don't know how to add the values of the list in the .json to the tensor. Which dimension should I use? Will the system work at all, if I change the shape of the input?
The function getitem can return anything, so you can return a tuple instead of just images :
def __getitem__(self, index):
path = ...
# load your 6 images
imgs = torch.stack( ... )
# load your boolean metadata
metadata = load_json_data( ... )
# return them both
return (imgs, metadata)
You will need to make metadata a tensor before returning it, otherwise I expect that pytorch will complain about not being able to collate (i.e stack) them to make batches
"Will the system work" is a question only you can answer, since you did not provide the code of your ML model. I would bet on : "no but it won't require significant changes to work". Most likely you currently have a loop like
for imgs in dataloader:
# do some training
output = model(imgs)
...
And you will have to make it like
for imgs, metadata in dataloader:
# do some training
output = model(imgs)
...
I created a custom layer in python so that I can feed the data directly.
but I noticed it runs extremely slow and the GPU usage is at most 1% ( the memory is allocated, i.e. I can see that when I run the script, it allocates 2100MB VRAM and terminating the training, frees around 1G.
I'm not sure if this is an expected behavior or I'm doing something wrong.
Here is the script I wrote (based on this former pr) :
import json
import caffe
import numpy as np
from random import shuffle
from PIL import Image
class MyDataLayer(caffe.Layer):
"""
This is a simple datalayer for training a network on CIFAR10.
"""
def setup(self, bottom, top):
self.top_names = ['data', 'label']
# === Read input parameters ===
params = eval(self.param_str)
# Check the paramameters for validity.
check_params(params)
# store input as class variables
self.batch_size = params['batch_size']
# Create a batch loader to load the images.
self.batch_loader = BatchLoader(params, None)
# === reshape tops ===
# since we use a fixed input image size, we can shape the data layer
# once. Else, we'd have to do it in the reshape call.
top[0].reshape(self.batch_size, 3, params['im_height'], params['im_width'])
# this is for our label, since we only have one label we set this to 1
top[1].reshape(self.batch_size, 1)
print_info("MyDataLayer", params)
def forward(self, bottom, top):
"""
Load data.
"""
for itt in range(self.batch_size):
# Use the batch loader to load the next image.
im, label = self.batch_loader.load_next_image()
# Add directly to the caffe data layer
top[0].data[itt, ...] = im
top[1].data[itt, ...] = label
def reshape(self, bottom, top):
"""
There is no need to reshape the data, since the input is of fixed size
(rows and columns)
"""
pass
def backward(self, top, propagate_down, bottom):
"""
These layers does not back propagate
"""
pass
class BatchLoader(object):
"""
This class abstracts away the loading of images.
Images can either be loaded singly, or in a batch. The latter is used for
the asyncronous data layer to preload batches while other processing is
performed.
labels:
the format is like :
png_data_batch_1/leptodactylus_pentadactylus_s_000004.png 6
png_data_batch_1/camion_s_000148.png 9
png_data_batch_1/tipper_truck_s_001250.png 9
"""
def __init__(self, params, result):
self.result = result
self.batch_size = params['batch_size']
self.image_root = params['image_root']
self.im_shape = [params['im_height'],params['im_width']]
# get list of images and their labels.
self.image_labels = params['label']
#getting the list of all image filenames along with their labels
self.imagelist = [line.rstrip('\n\r') for line in open(self.image_labels)]
self._cur = 0 # current image
# this class does some simple data-manipulations
self.transformer = SimpleTransformer()
print ("BatchLoader initialized with {} images".format(len(self.imagelist)))
def load_next_image(self):
"""
Load the next image in a batch.
"""
# Did we finish an epoch?
if self._cur == len(self.imagelist):
self._cur = 0
shuffle(self.imagelist)
# Load an image
image_and_label = self.imagelist[self._cur] # Get the image index
#read the image filename
image_file_name = image_and_label[0:-1]
#load the image
im = np.asarray(Image.open(self.image_root +'/'+image_file_name))
#im = scipy.misc.imresize(im, self.im_shape) # resize
# do a simple horizontal flip as data augmentation
flip = np.random.choice(2)*2-1
im = im[:, ::flip, :]
# Load and prepare ground truth
#read the label
label = image_and_label[-1]
#convert to onehot encoded vector
#fix: caffe automatically converts the label into one hot encoded vector. so we only need to simply use the decimal number (i.e. the plain label number)
#one_hot_label = np.eye(10)[label]
self._cur += 1
return self.transformer.preprocess(im), label
def check_params(params):
"""
A utility function to check the parameters for the data layers.
"""
required = ['batch_size', 'image_root', 'im_width', 'im_height', 'label']
for r in required:
assert r in params.keys(), 'Params must include {}'.format(r)
def print_info(name, params):
"""
Ouput some info regarding the class
"""
print ("{} initialized for split: {}, with bs: {}, im_shape: {}.".format(
name,
params['image_root'],
params['batch_size'],
params['im_height'],
params['im_width'],
params['label']))
class SimpleTransformer:
"""
SimpleTransformer is a simple class for preprocessing and deprocessing
images for caffe.
"""
def __init__(self, mean=[125.30, 123.05, 114.06]):
self.mean = np.array(mean, dtype=np.float32)
self.scale = 1.0
def set_mean(self, mean):
"""
Set the mean to subtract for centering the data.
"""
self.mean = mean
def set_scale(self, scale):
"""
Set the data scaling.
"""
self.scale = scale
def preprocess(self, im):
"""
preprocess() emulate the pre-processing occuring in the vgg16 caffe
prototxt.
"""
im = np.float32(im)
im = im[:, :, ::-1] # change to BGR
im -= self.mean
im *= self.scale
im = im.transpose((2, 0, 1))
return im
def deprocess(self, im):
"""
inverse of preprocess()
"""
im = im.transpose(1, 2, 0)
im /= self.scale
im += self.mean
im = im[:, :, ::-1] # change to RGB
return np.uint8(im)
And in my train_test.prototxt file I have :
name: "CIFAR10_SimpleTest_PythonLayer"
layer {
name: 'MyPythonLayer'
type: 'Python'
top: 'data'
top: 'label'
include {
phase: TRAIN
}
python_param {
#the python script filename
module: 'mypythonlayer'
#the class name
layer: 'MyDataLayer'
#needed parameters in json
param_str: '{"phase":"TRAIN", "batch_size":10, "im_height":32, "im_width":32, "image_root": "G:/Caffe/examples/cifar10/testbed/Train and Test using Pycaffe", "label": "G:/Caffe/examples/cifar10/testbed/Train and Test using Pycaffe/train_cifar10.txt"}'
}
}
layer {
name: 'MyPythonLayer'
type: 'Python'
top: 'data'
top: 'label'
include {
phase: TEST
}
python_param {
#the python script filename
module: 'mypythonlayer'
#the class name
layer: 'MyDataLayer'
#needed parameters in json
param_str: '{"phase":"TEST", "batch_size":10, "im_height":32, "im_width":32, "image_root": "G:/Caffe/examples/cifar10/testbed/Train and Test using Pycaffe", "label": "G:/Caffe/examples/cifar10/testbed/Train and Test using Pycaffe/test_cifar10.txt"}'
}
}
Whats wrong here?
Your data layer is not efficient enough and it takes most of the training time (you should try caffe time ... to get a more detailed profiling). At each forward pass you are waiting for the python layer to read batch_size images from disk one after the other. This can take forever.
You should consider using Multiprocessing to perform the reading at the background while the net is processing the previous batches: this should give you good CPU/GPU utilization.
See this example for multiprocessing python data layer.
Python layers are executed on CPU not the GPU so it's slow because things have to keep going between the CPU and GPU when training. That's also why you see low gpu usage because its waiting on the cpu to execute the python layer.
I am trying to bind the ENTER key to the email password entry box. That way when I have entered all three items I can press enter to call the callback() function. The other issue I have is with the .get() method. It does not seem to assign the values I typed into the entry boxes to the variables I defined in my code.
from Tkinter import *
root = Tk()
# grabs the values in the entry boxes and assigns them to variablse
def callback():
steamUser = steamUserW.get()
steamPass = steamPassW.get()
emailPass = emailPassW.get()
root.destroy()
# labels for each entry
Label(root, text="Steam Username").grid(row=0)
Label(root, text="Steam Password").grid(row=1)
Label(root, text="Email Password").grid(row=2)
# entry and button widgets
steamUserW = Entry(root)
steamPassW = Entry(root, show="*")
emailPassW = Entry(root, show="*")
submit = Button(root, text="Submit", command=callback)
# bind the ENTER key to callback function
emailPassW.bind("<Return>", callback)
# space out the widgets
steamUserW.grid(row=0, column=1)
steamPassW.grid(row=1, column=1)
emailPassW.grid(row=2, column=1)
submit.grid(row=3, column=1)
root.mainloop()
print steamUser
EDIT, my new code fixes the .get() issue but I still have a binding issue with the ENTER keys
from Tkinter import *
class gui:
def __init__(self, master):
self.master = master
# labels for each entry
Label(self.master, text="Steam Username").grid(row=0)
Label(self.master, text="Steam Password").grid(row=1)
Label(self.master, text="Email Password").grid(row=2)
# button widget
self.steamUserW = Entry(self.master)
self.steamPassW = Entry(self.master, show="*")
self.emailPassW = Entry(self.master, show="*")
self.submit = Button(self.master, text="Submit", command=self.assign)
# bind the ENTER key to callback function
self.emailPassW.bind("<Return>", self.assign)
self.emailPassW.bind("<KP_Enter>", self.assign)
# space out the widgets
self.steamUserW.grid(row=0, column=1)
self.steamPassW.grid(row=1, column=1)
self.emailPassW.grid(row=2, column=1)
self.submit.grid(row=3, column=1)
# grabs the values in the entry boxes and assigns them to variablse
def assign(self):
self.steamUser = self.steamUserW.get()
self.steamPass = self.steamPassW.get()
self.emailPass = self.emailPassW.get()
self.close()
# closes GUI window
def close(self):
self.master.destroy()
root = Tk()
userGui = gui(root)
root.mainloop()
print userGui.steamUser
The original error with the assign not working was because you were assigning the values to local variables. It was working, but no function outside of the callback could see them. The fix is to either declare the variables as global, or re-architect your code to use classes, and make the variables attributes of the class.
The problem with the binding is that your callback needs to accept an argument. When you use bind, the function that is called will always be passed an argument. This argument is an object representing the event. From this object you can get the widget that triggered the event, the x/y coordinates of the cursor, and several other bits of information.
For your original code, you can fix it like this:
def callback(event):
global steamUser, steamPass, emailPass
steamUser = steamUserW.get()
steamPass = steamPassW.get()
emailPass = emailPassW.get()
root.destroy()
Since you've switched to using a class, you have to have one argument for the event and one argument for self:
def callback(self, event):
...
This behavior of passing in an argument is well documented. For example, the effbot page on Events and Bindings says:
"If an event matching the event description occurs in the widget,
the given handler is called with an object describing the event."
Assignment works, but only to a set of variables local to callback() scope
That means, you do not "see" these variables after the function terminates.
Bind each of the ENTER and NumPad-ENTER keys, otherwise just half-done
# COMMAND prepared as <lambda>-container
# to show both auto-injected
# and ad-hoc added variable <placeholder>-s
a_COMMAND2bind = ( lambda aTkInjectedBindEVENT = None, # .SET a <placeholder>
aParameter1 = None, # .SET a <placeholder>
aParameter2 = None, # .SET a <placeholder>
anotherPlaceholderVoidVAR = "?": # .SET another if needed
callback( aTkInjectedBindEVENT ) # .ACT on <<Event>>
or # trick to chain
print( "DEBUG:: aParameter1 == ", aParameter1 )
or
print( "DEBUG:: aParameter2 == ", aParameter2 )
or
call_other_Funct( "Log: " # .ACT on <<Event>>
+ time.ctime()
)
)
# --.|||||||||
root.event_add( "<<anEnterKeyVirtualEVENT>>", "<KeyPress-Return>", # setup as-<<aVirtualEVENT>>
"<KeyPress-KP_Enter>"
)
# --.||||
root.bind( "<<anEnterKey_VirtualEVENT>>", a_COMMAND2bind ) # .bind aCommandAsLAMBDA
Rather wrap into Class and process with smart context-handling
Your code invokes your def callback(): construct in two different contexts
as a Button( ... , command = callback )
as an Entry widget .bind( ..., callback )
as referred, Tkinter auto-injects anEventOBJECT upon an event occurence, to allow a context-full processing:
# <anEventOBJECT>.char on-{ <KeyPress> | <KeyRelease> }
# .height on-{ <Configure> }
# .width on-{ <Configure> }
# .keysym on-{ <KeyPress> | <KeyRelease> }
# .keysym_num on-{ <KeyPress> | <KeyRelease> }
# .num on-{ <Mouse-1> | <Mouse-2> | ... } 4,5 == <MouseWheel> <--test on target platform O/S
# .serial <-- system-assigned Integer
# .time <-- system-assigned Integer ( .inc each msec )
# .widget <-- system-assigned <widget>-instance
# .x <-- system-assigned <Event>-in-<widget>-mouse-location.x
# .y <-- system-assigned <Event>-in-<widget>-mouse-location.y
# .x_root <-- system-assigned <Event>-on-<Screen>-mouse-location.x
# .y_root <-- system-assigned <Event>-on-<Screen>-mouse-location.y
So the code, as originally proposed, would have hard time to handle each of the different event-context(s) inside the same function.
Better structure into different events/handlers, your event-handling will get simpler per each context.
With the help of user3666197 I was able to figure some of it out and through a bit of googling I came up with a solution.
I had to create a gui class so I could easily store and access the three user inputs.
As for the bindings, the error I got was that the callback() (which I renamed to assign() was taking in too many arguments. The error is exactly TypeError: assign() takes exactly 1 argument (2 given). So I fixed this by allowing as many arguments to be passed into the assign() function, def assign(self, *args):. I am actually not too sure why I got this error after pressing enter, if someone knows please let me know!
from Tkinter import *
class gui:
def __init__(self, master):
self.master = master
# labels for each entry
Label(self.master, text="Steam Username").grid(row=0)
Label(self.master, text="Steam Password").grid(row=1)
Label(self.master, text="Email Password").grid(row=2)
# button widget
self.steamUserW = Entry(self.master)
self.steamPassW = Entry(self.master, show="*")
self.emailPassW = Entry(self.master, show="*")
self.submit = Button(self.master, text="Submit", command=self.assign)
# bind the ENTER key to callback function
self.emailPassW.bind("<Return>", self.assign)
self.emailPassW.bind("<KP_Enter>", self.assign)
# space out the widgets
self.steamUserW.grid(row=0, column=1)
self.steamPassW.grid(row=1, column=1)
self.emailPassW.grid(row=2, column=1)
self.submit.grid(row=3, column=1)
# grabs the values in the entry boxes and assigns them to variablse
def assign(self, *args):
self.steamUser = self.steamUserW.get()
self.steamPass = self.steamPassW.get()
self.emailPass = self.emailPassW.get()
self.close()
# closes GUI window
def close(self):
self.master.destroy()
root = Tk()
userGui = gui(root)
root.mainloop()
print userGui.steamUser
print userGui.emailPass