GetSelection ComboBox - combobox

I can't figure out what else I need for the combobox to select
from my list as I type. Eventually I'm going to add SetInsertionPoint.
But for now, my item selected is allways -1
self.filter = wx.ComboBox(self, wx.ID_ANY, choices = '', style=wx.CB_DROPDOWN)
def OnTextChanged(self, event):
sel = self.filter.GetSelection()
print 'OnItemSelected %s' % sel

This other SO answer has a custom control that might work for you:
Auto-Completion In wxPython wxComboBox
You may also get ideas from this wxPython wiki article
http://wiki.wxpython.org/TextCtrlAutoComplete
I also noticed that the masked combo box may have this feature itself, according to the docs: http://www.wxpython.org/docs/api/wx.lib.masked.combobox-module.html which says the following
BaseMaskedComboBox - Base class for generic masked edit comboboxes; allows auto-complete of values.

To use the GetSelection() alone, you need to set the ComboBox to read only. It's a nice way to
query by hitting one charactor. Using SetInsertionPoint and SetMark keeps the curser to the next string of your query. I used the example Mike suggested •Auto-Completion In wxPython wxComboBox
and modified my code to used these instances. Since I always use boxsizers and open functions I needed to do away with the wx.EVT_TEXT event. Here's how it works:
## copy/paste to text file
'''
73,"N WASHINGTON ST"
95,"BRIAR CREEK RD"
97,"N INDEPENDENCE AVE"
09,"N ADAMS ST"
13,"N JEFFERSON ST"
19,"N MADISON ST"
21,"QUAIL CREEK DR"
24,"INDIAN DR"
12,"CHEROKEE TRAIL"
50,"CORONADO TRAIL"
'''
import wx, os
from cStringIO import StringIO
import csv
class MainFrame(wx.Frame):
def __init__(self, parent, choices=[], style=0):
wx.Frame.__init__(self,None,wx.ID_ANY,title='test combo autocomplete',size=(225, 70))
self.vbox= wx.BoxSizer(wx.VERTICAL)
self.background = wx.Panel(self)
self.OpenDir = wx.TextCtrl(self,style=wx.PROCESS_ENTER|wx.TE_CENTRE)
self.filter = wx.ComboBox(self, wx.ID_ANY, style=wx.CB_DROPDOWN)
self.OpenDir.Bind(wx.EVT_LEFT_UP,self.OnChooseRoot)
self.filter.Bind(wx.EVT_TEXT, self.OnTextChanged)
hsizer1 = wx.BoxSizer(wx.HORIZONTAL)
hsizer1.Add(self.OpenDir,1)
hsizer2 = wx.BoxSizer(wx.HORIZONTAL)
hsizer2.Add(self.filter,1)
self.vbox.Add(hsizer1,proportion = 0,flag = wx.EXPAND)
self.vbox.Add(hsizer2,proportion = 0,flag = wx.EXPAND)
self.SetSizer(self.vbox)
self.Show()
self.OpenDir.SetValue("click to open directory")
def OnTextChanged(self, event):
def refresh():
wnd = self.filter
currentText = event.GetString()
while wnd:
print currentText
wnd.Layout()
print wnd.Layout()
wnd = wnd.GetParent()
self.filter.SetInsertionPoint(len(currentText))
self.filter.SetMark(len(currentText), len(self.choices))
self.filter.Refresh()
refresh()
event.Skip()
def OnChooseRoot(self, event):
self.dirname=""
dlg = wx.FileDialog(self, "choose a file to open", self.dirname,
"", "*.*", wx.OPEN)
if dlg.ShowModal() == wx.ID_OK:
self.filename = dlg.GetFilename()
self.dirname = dlg.GetDirectory()
self.pathname = dlg.GetPath()
self.f = open(os.path.join(self.dirname, self.filename), 'r')
self.text = self.f.read()
labeltop = self.dirname + '\\'
self.OpenDir.SetValue(labeltop + self.filename)
sources = [StringIO(self.text)]
for i, source in enumerate(sources):
c = list(csv.reader(source))
self.choices = [x[1] for x in c]
self.filter.SetItems(self.choices)
app = wx.App(redirect=False)
frame = MainFrame(None)
app.MainLoop()

Related

Add M2M field using create(): Django

I have a lot of doubts about managing the M2m field, I finally got a solution to add that data to a model, but there are still some issues, give me a solution to overcome this,
class CourseListSerializer(serializers.ModelSerializer):
instructors = serializers.SerializerMethodField()
image = FileField()
keyarea = CourseKeyAreaSerializer
subject = CourseSubjectsSerializer
sections = serializers.ListField(write_only=True)
beneficiaries = serializers.ListField(write_only=True)
section = CourseSectionSerializers
beneficiary = CourseBeneficiarySerializer
def create(self, validated_data):
data = validated_data
try:
new = Course.objects.create(image=data['image'], name=data['name'], description=data['description'], is_free=data['is_free'],
keyarea=data['keyarea'], subject=data['subject'])
new.save()
beneficiary_data = data['beneficiaries']
new.beneficiary.set(*[beneficiary_data])
section_data = data['sections']
new.section.set(*[section_data])
return new
except Exception as e:
e = "invalid data"
return e
here first creating the "new" object after that to set the M2M field like
"new.beneficiary.set(*[beneficiary_data])"
but is there any way to add beneficiary and section like this
"new = Course.objects.create(image=data['image'],name=data['name'], description=data['description'],is_free=data['is_free'],....)"

Choregraphe: How to change NAO's Chest and Feet LEDs

Pretty much what the title says. How can i change NAO's Chest and Feet LEDs. I know they support RGB but how do i command what colours they stay at?
I found a way to do it. It was actually quite simple.
I altered the code of the "Eye LEDs" box.
If you double click it it will show you 2 other boxes, "Color Edit" and "Eyes LEDs".
I simply altered the code of the second "Eyes LEDs" box with this one:
class MyClass(GeneratedClass):
def __init__(self):
GeneratedClass.__init__(self, False)
def onLoad(self):
self.fadeOps = []
self.leds = self.session().service("ALLeds")
def onUnload(self):
#~ puts code for box cleanup here
pass
def onInput_color(self, p):
if( self.getParameter("Side") == "Left" ):
sGroup = "AllLeds"
elif( self.getParameter("Side") == "Right" ):
sGroup = "AllLeds"
else:
sGroup = "AllLeds"
fadeOp = self.leds.fadeRGB(sGroup, 256*256*p[0] + 256*p[1] + p[2], self.getParameter("Duration (s)"), _async=True)
self.fadeOps.append(fadeOp)
fadeOp.wait()
self.fadeOps.remove(fadeOp)
if( self.fadeOps == [] ):
self.onDone() # activate output of the box
Technically all I did is change all the "sGroup = ... " to sGroup = "AllLeds"

Returning a dictionary from a file

I have have written this code defining a class
class OrderRecord:
"""Defines an OrderRecord class, suitable for use in keeping track of order records"""
import tools2
def __init__(self, string):
"""Creates a new OrderRecord object"""
string = string.split(',')
self.date = string[0]
self.location = string[1]
self.name = string[2]
self.colour = string[3]
self.order_num = string[4]
self.cost = 0
def cost_of_order(self):
"""Creates a list of the name and adds up the cost of each letter"""
letter = list(self.name)
for let in letter:
self.cost = self.cost + self.tools2.letter_price(let, self.colour)
return self.cost
def __str__(self):
"""Calls the cost_of_order function and returns the split string in the required format"""
self.cost = self.cost_of_order()
return("Date: {0}\nLocation: {1}\nName: {2}\nColour: \
{3}\nOrder Num: {4}\nCost: {5:.2f}".format(self.date, self.location, \
self.name, self.colour, self.order_num, self.cost))
Now I need to write a function that reads a file containing the following:
20130902,Te Rakipaewhenua,Vinas,parauri,8638
20130909,Te Papaioea,McClary,kikorangi,11643
20131215,Kapiti,Labrie,kikorangi,65291
20141106,Waihopai,Labrie,ma,57910
and returns a dictionary that has the location as the key and lists of OrderRecords as the values.
I know this isn't too hard of a task but I have been stuck on this for awhile because I can't get my head around what to do for it.
Any help would be appreciated.
Maybe something like this. It is not the solution but it has what you need with some modifications.
import collections
dct_result = collections.defaultdict(list)
for line in open('file_path'):
fields = line.split(',')
# index 1 being the second column
dct_result[field(1)].append(OrderRecord( some args ))

Passing values between forms with npyscreen

I am trying to create a simple npyscreen curses application in python that requests user input on one screen, and then verifies it for the user on another screen.
Mostly, this is an effort to understand how values are stored and retrieved from within npyscreen. I am sure I am missing something simple, but I have been unable to find (or understand?) the answer within the documentation.
Sample code below which will not pass the value properly:
#!/usr/bin/env python3.5
import npyscreen as np
class EmployeeForm(np.Form):
def afterEditing(self):
self.parentApp.switchForm('CONFIRMFM')
def create(self):
self.myName = self.add(np.TitleText, name='Name')
self.myDepartment = self.add(np.TitleSelectOne, scroll_exit=True, max_height=3, name='Department', values = ['Department 1', 'Department 2', 'Department 3'])
self.myDate = self.add(np.TitleDateCombo, name='Date Employed')
class EmployeeConfirmForm(np.Form):
def afterEditing(self):
self.parentApp.setNextForm(None)
def create(self):
self.value = None
self.wgName = self.add(np.TitleText, name = "Name:",)
self.wgDept = self.add(np.TitleText, name = "Dept:")
self.wgEmp = self.add(np.TitleText, name = "Employed:")
def beforeEditing(self):
if self.value:
self.name = "Is this correct?"
self.wgName.value = self.myName.value
self.wgDept.value = self.myDepartment.value
self.wgEmp.value = self.myDate.value
def on_cancel(self):
self.parentApp.switchFormPrevious()
class myApp(np.NPSAppManaged):
def onStart(self):
self.addForm('MAIN', EmployeeForm, name='Employee Entry')
self.addForm('CONFIRMFM', EmployeeConfirmForm, name='Employee Confirmation')
if __name__ == '__main__':
TestApp = myApp().run()
I haven't found a straightforward way to directly pass variables between forms. However, you can work around this by using variables that have a global scope among forms.
The NPSAppManaged app class runs completely encapsulated, so if you try to declare global variables at the top of the Python file, the forms within will not have access to them. Instead, declare the variables inside the NPSAppManaged app class before the onStart method as shown below.
class myApp(np.NPSAppManaged):
# declare variables here that have global scope to all your forms
myName, myDepartment, myDate = None, None, None
def onStart(self):
self.addForm('MAIN', EmployeeForm, name='Employee Entry')
self.addForm('CONFIRMFM', EmployeeConfirmForm, name='Employee Confirmation')
if __name__ == '__main__':
TestApp = myApp().run()
You can then access these variables using self.parentApp.[variable name] as follows:
class EmployeeConfirmForm(np.Form):
def afterEditing(self):
self.parentApp.setNextForm(None)
def create(self):
self.add(np.FixedText, value = "Is this correct?")
self.wgName = self.add(np.TitleText, name = "Name:", value = self.parentApp.myName)
self.wgDept = self.add(np.TitleText, name = "Dept:", value = self.parentApp.myDepartment)
self.wgEmp = self.add(np.TitleText, name = "Employed:", value = self.parentApp.myDate)
def on_cancel(self):
self.parentApp.switchFormPrevious()
Note: you don't need to have a separate beforeEditing method since the values will be loaded directly into EmployeeConfirmForm during the create method from the app class global variables.
One way to do this is to use getForm before switchForm to pass the values. The following works for me using python2 to pass the name. Passing other values should be similar. I'm very much learning this myself but please comment if you have further questions.
import npyscreen as np
class EmployeeForm(np.ActionForm):
def create(self):
self.myName = self.add(np.TitleText, name='Name')
self.myDepartment = self.add(np.TitleSelectOne, scroll_exit=True, max_height=3, name='Department', values = ['Department 1', 'Department 2', 'Department 3'])
self.myDate = self.add(np.TitleDateCombo, name='Date Employed')
def afterEditing(self):
self.parentApp.getForm('CONFIRMFM').wgName.value = self.myName.value
self.parentApp.switchForm('CONFIRMFM')
class EmployeeConfirmForm(np.Form):
def afterEditing(self):
self.parentApp.setNextForm(None)
def create(self):
self.value = None
self.wgName = self.add(np.TitleFixedText, name = "Name:",)
self.wgDept = self.add(np.TitleText, name = "Dept:")
self.wgEmp = self.add(np.TitleText, name = "Employed:")
def on_cancel(self):
self.parentApp.switchFormPrevious()
class myApp(np.NPSAppManaged):
def onStart(self):
self.addForm('MAIN', EmployeeForm, name='Employee Entry')
self.addForm('CONFIRMFM', EmployeeConfirmForm, name='Employee Confirmation')
if __name__ == '__main__':
TestApp = myApp().run()
Assign values (including the value returned by addForm) to self.whatever.
So if you do
self.myAppValue = 2
self.mainForm = self.addForm('MAIN', MainForm, ...)
self.form2 = self.addForm('FORM2', Form2, ...)
you can use these in any form
self.parentApp.myAppValue
self.parentApp.mainForm.main_form_widget.main_form_value
And in myApp() you can do
self.mainForm.main_form_widget.main_form_value
I had the same problems during development as the documentation is not very detailed about passing values between forms.
I have added a few modification, the first one was changing Form to ActionForm in the confirmation form to have access to ok and cancel buttons. Secondly, the values on the confirmation form should not be editable as this is a confirmation. You can press cancel to edit on the previous form. The last one was passing the first element of the department list rather than the value - it would be just a list index. I hope it helps a little.
#!/usr/bin/env python3.5
import npyscreen as np
class EmployeeForm(np.Form):
def create(self):
self.myName = self.add(np.TitleText, name='Name')
self.myDepartment = self.add(np.TitleSelectOne, scroll_exit=True, max_height=3, name='Department', values = ['Department 1', 'Department 2', 'Department 3'])
self.myDate = self.add(np.TitleDateCombo, name='Date Employed')
def afterEditing(self):
self.parentApp.switchForm('CONFIRMFM')
self.parentApp.getForm('CONFIRMFM').wgName.value = self.myName.value
self.parentApp.getForm('CONFIRMFM').wgDept.value = self.myDepartment.values[0]
self.parentApp.getForm('CONFIRMFM').wgEmp.value = self.myDate.value
class EmployeeConfirmForm(np.ActionForm):
def create(self):
self.add(np.FixedText, value="Is this correct?", editable=False)
self.wgName = self.add(np.TitleText, name = "Name:", editable=False)
self.wgDept = self.add(np.TitleText, name = "Dept:", editable=False)
self.wgEmp = self.add(np.TitleText, name = "Employed:", editable=False)
def on_ok(self):
self.parentApp.setNextForm(None)
def on_cancel(self):
self.parentApp.switchFormPrevious()
class myApp(np.NPSAppManaged):
def onStart(self):
self.addForm('MAIN', EmployeeForm, name='Employee Entry')
self.addForm('CONFIRMFM', EmployeeConfirmForm, name='Employee Confirmation')
if __name__ == '__main__':
TestApp = myApp().run()

Python 2.7: Tkinter/ttk Linked ComboBoxes

I've made a simple GUI using a GUI editor called PAGE. It contains two Tkinter.ttk combo boxes. My first combo box gets its values as column names from a connected sqlite database table. When I choose a column name from first combo box, second combo box should update its values automatically related to first values.
BTW, my codes below work properly in this current condition. If I choose a value from first combo box, It'll print the values to interactive shell. But these values should insert into second combo box. Does anyone know how can I figure it out?
Any help is greatly appreciated. Thanks in advance...
Here are my GUI codes:
from pysqlite2 import dbapi2 as db
from Tkinter import *
import ttk
def getdata():
global colnames
conn = db.connect("blabla.sqlite")
cur = conn.execute("select * from states")
col = cur.description
colnames = [abu[0] for abu in col]
initcombo = getdata()
def vp_start_gui():
global val, w, root
root = Tk()
root.title('Linked Comboboxes')
root.geometry('301x230+556+208')
set_Tk_var()
w = New_Toplevel_1 (root)
init()
root.mainloop()
w = None
def create_New_Toplevel_1 (root):
global w, w_win
if w:
return
w = Toplevel (root)
w.title('New_Toplevel_1')
w.geometry('301x230+556+208')
set_Tk_var()
w_win = New_Toplevel_1 (w)
init()
return w_win
def destroy_New_Toplevel_1 ():
global w
w.destroy()
w = None
def set_Tk_var():
global combobox
combobox = StringVar()
def init():
pass
class New_Toplevel_1:
def __init__(self, master=None):
style = ttk.Style()
theme = style.theme_use()
default = style.lookup(theme, 'background')
master.configure(background=default)
def choose1(event=None):
conn2 = db.connect("blabla.sqlite")
cur2 = conn2.execute("select %s from states" % self.TCombobox1.get())
results = cur2.fetchall()
for row in results:
print row
self.TCombobox1 = ttk.Combobox (master, state='readonly')
self.TCombobox1.place(relx=0.03,rely=0.13,relheight=0.09,relwidth=0.48)
self.TCombobox1["values"] = colnames
self.TCombobox1.set("Choose one...")
self.TCombobox1.bind("<<ComboboxSelected>>", choose1)
self.TCombobox2 = ttk.Combobox (master, state='readonly')
self.TCombobox2.place(relx=0.03,rely=0.33,relheight=0.09,relwidth=0.48)
self.TLabel1 = ttk.Label (master)
self.TLabel1.place(relx=0.03,rely=0.83,height=19,width=28)
self.TLabel1.configure(relief="flat")
self.TLabel1.configure(text='''Info:''')
self.TButton1 = ttk.Button (master)
self.TButton1.place(relx=0.63,rely=0.22,height=25,width=76)
self.TButton1.configure(takefocus="")
self.TButton1.configure(text='''Run''')
if __name__ == '__main__':
vp_start_gui()
Set the 'results' as the value of the 'values' config of the second combobox.
def choose1(event=None):
conn2 = db.connect("blabla.sqlite")
cur2 = conn2.execute("select %s from states" % self.TCombobox1.get())
results = cur2.fetchall()
self.TCombobox2['values'] = results
for row in results:
print row

Resources