I've built a class for item selection with Tkinter Spinbox. I'd like to return the index of the selected item. Is that possible?
from Tkinter import *
class TestSpin():
def __init__(self, i_root, i_friendlist):
self.root = i_root
self.root.friend = Spinbox(self.root, values = i_friendlist)
self.root.friend.pack()
self.root.okbutton = Button(self.root, text='Ok', command = lambda: self.ack())
self.root.okbutton.pack()
def ack(self):
# here I'd like to have the index of selected item in friendlist
print "Index of "+self.root.friend.get()+" is [0 or 1 or 2]:", self.root.friend
# here I'd like to have the index of selected item in friendlist
self.root.destroy()
root = Tk()
list = ['Emma','Sarah','James']
app = TestSpin(root, list)
root.mainloop()
Thanks a lot for your advice. I tried self.root.friend.index(), but that method wants an argument which I do not understand.
There's no way to directly get the value from the widget, but it's just one line of python code:
index = i_fiendlist.index(self.root.friend.get())
Using your code, you need to save the value of the list:
class TestSpin():
def __init__(self, i_root,i_friendlist):
self._list = i_list
...
def ack(self):
value = self.root.friend.get()
index = self._list.index(value)
print "Index of " + value + " is " + str(index)
self.root.destroy()
Related
I set the number of spinboxes in the previous window and then, according to the code below, they are added in the next window, but when I click the button, I need to pick up the value from each generated spinbox, but at the moment the value is transmitted only from the last one.
How do I get the value from each spinbox?
Thank you!
class CreateSpuWindow(QMainWindow):
def __init__(self, value):
super().__init__()
uic.loadUi('ui/statement_spu_1.ui', self)
self.value = value # Quantity pf spinBoxes
for i in range(value):
self.spu_label = QLabel(self)
self.spu_label.setText(f"SPU №{i+1}. PP:")
self.quantity_pp = QSpinBox(self)
self.quantity_pp.setValue(1)
self.quantity_pp.setMinimum(1)
self.gridLayout_2.addWidget(self.spu_label, 2 * i, 0)
self.gridLayout_2.addWidget(self.quantity_pp, 2 * i, 1)
self.next_tu_spu_2Button.clicked.connect(self.next_wind_spu_btn)
self.back_btn.clicked.connect(self.back_btn_cl)
def next_wind_spu_btn(self):
data = []
# Get a value from spinbox
for i in str(self.quantity_pp.value()):
data.append(i)
print(data)
quantity_spu = self.value
self.ReadyTableSpuWindow = ReadyTableSpuWindow(quantity_spu)
self.ReadyTableSpuWindow.show()
self.close()
def back_btn_cl(self):
self.close()
self.QuantitySpuWindow = QuantitySpuWindow()
self.QuantitySpuWindow.show()
I'm having a problem on how can I remove an item from the list widget using a button and possibly how can I clear the widget after checking all the item.
py.file
class MenuScreen(Screen):
def add_item(self):
global lst
i = 0
if self.ids.inp.text == "":
close_button = MDFlatButton(text="Okay", on_release=self.close_dialog)
self.dialog = MDDialog(title="Invalid", text="No item added",
size_hint=(0.7, 1), buttons=[close_button])
self.dialog.open()
else:
list_items.append(self.ids.inp.text)
self.ids.inp.text = ''
for x in range(len(list_items)):
lst = OneLineAvatarIconListItem(text=list_items[i])
i += 1
self.ids.list.add_widget(lst)
def close_dialog(self, obj):
self.dialog.dismiss()
def remove_item(self):
pass
Example image:
For removing the item that is selected you can use self.ids.list.children to access all the items in your list and simply use remove_widget() to remove that item.And to clear your list after all the items are selected,you can use clear_widgets().
I cant print the key value of the dic when I print the value of each list
I tried with the code I wrote down!
import tkinter as tk
from tkinter import ttk
limit_before_list = [0]
max_posts_list = [0]
max_comments_list = [0]
limit_before = 'limit_before'
max_posts = 'max_posts'
max_comments = 'max_comments'
def mostrar_nombre(event):
listbox = event.widget
index = listbox.curselection()
value = listbox.get(index[0])
print(pestaña_text)
print(value)
pestañas = {
limit_before: list(range(0, 160, 10)),
max_posts: list(range(0, 410, 10)),
max_comments: list(range(0, 4100, 100)),
}
note = ttk.Notebook()
for pestaña, items in pestañas.items():
frame = ttk.Frame(note)
note.add(frame, text=pestaña)
listbox = tk.Listbox(frame, exportselection=False)
listbox.grid(row=0, column=0)
listbox.bind("<<ListboxSelect>>", mostrar_nombre)
if pestaña == limit_before:
pestaña_text = limit_before
elif pestaña == max_posts:
pestaña_text = max_posts
elif pestaña == max_comments:
pestaña_text = max_comments
for item in items:
listbox.insert(tk.END, item)
note.pack()
note.mainloop()
I excpected something like with the prints. The problem is when I print, I have the same Key for all listbox
>>>limit_before
>>>50
>>>max_post
>>>60
>>>max_comments
>>>100
>>>max_post
>>>30
....
Creating the variable pestaña_text is not handy in this case. It is defined in the main scope but it is overridden in the for loop and keeps the last value max_comments:
for pestaña, items in pestañas.items():
...
if pestaña == limit_before:
pestaña_text = limit_before
elif pestaña == max_posts:
pestaña_text = max_posts
elif pestaña == max_comments:
pestaña_text = max_comments
So when you call it next, in the the function mostrar_nombre, you will only get max_comments.
You can delete this for loop and use directly the selected tab text attribute by referring to the active tab of the NoteBook object with the method select:
def mostrar_nombre(event):
listbox = event.widget
index = listbox.curselection()
value = listbox.get(index[0])
print(note.tab(note.select(), "text"))
print(value)
Some doc here and another similar question here.
I am trying to add a value to a instance list in python but want to access it dynamically from within a method.
I cannot use dictionaries as I am trying to speed up the sorting of separate lists (boxes) rather than one large list.
Can anybody show me the correct way to do the following?
class Boxes:
def __init__(self):
self.box1 = []
self.box2 = []
#....
self.box10 = []
def addToBox(self, value):
box = self.determineBoxToUse(value)
## box = 2
varname = "box", box ## box2
self.varname.insert(0, value)
def determineBoxToUse(self, value):
## for this example returns 2
return 2
def dumpBox(self):
print self.box2
Boxes = Boxes();
Boxes.addToBox("123.001234")
Boxes.dumpBox()
Error: AttributeError: Boxes instance has no attribute 'varname'
Thanks
You can use hasattr and getattr, although many might suggest you should pursue a different solution.
def addToBox(self, value):
box = self.determineBoxToUse(value)
## box = 2
varname = "box{}".format(box) ## box2
if hasattr(self, varname):
getattr(self, varname).insert(0,value)
Demo:
>>> class Boxes:
def __init__(self):
self.box1 = []
self.box2 = []
#....
self.box10 = []
def addToBox(self, value):
box = self.determineBoxToUse(value)
## box = 2
varname = "box{}".format(box) ## box2
if hasattr(self, varname):
getattr(self, varname).insert(0,value)
def determineBoxToUse(self, value):
## for this example returns 2
return 2
def dumpBox(self):
print self.box2
>>> Boxes = Boxes()
>>> Boxes.addToBox("123.001234")
>>> Boxes.dumpBox()
['123.001234']
>>>
I have a checkboxCtrlmixin, and what I want is to show the selected values of the checkboxCtrlmixin. Is there any special function in checkboxctrlmixin that shows what values are selected?
My code:
class TestListCtrl(wx.ListCtrl, listmix.CheckListCtrlMixin, listmix.ListCtrlAutoWidthMixin):
def __init__(self,*args,**kwargs):
wx.ListCtrl.__init__(self,*args,**kwargs)
listmix.CheckListCtrlMixin.__init__(self)
listmix.ListCtrlAutoWidthMixin.__init__(self)
self.setResizeColumn(3)
class rulesFrame(wx.Frame):##open about frame
""""""
#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
wx.Frame.__init__(self, None, wx.ID_ANY, "Choose Rules")
panel = wx.Panel(self)##create panel
prules=subprocess.check_output("perl ruleFinder.pl dataset24819.arff rules_test1Fold0w4_sample00ll1.dat", shell=True)
prules = prules.split()
ruleiden = [x for x in prules if x!='159']
ruleiden = list(set(ruleiden))
sortrule = [int(x) for x in ruleiden]
sortrule.sort()
with open('rules_test1Fold0w4_sample00ll1.dat') as fileobj:
lines = list(fileobj)
actualrules=''
##sortrule=[item+1 for item in sortrule]
##print sortrule
for index in sortrule:
actualrules += lines[index]
actualrules = actualrules.split('\n')
wx.Button(panel,label="Show Selected Rules",pos=(170,520),size=(200,25))
self.list = TestListCtrl(panel,size=(1000,500), style = wx.LC_REPORT)
self.list.InsertColumn(0,'Rules')
self.list.SetColumnWidth(0,500)
for i in actualrules:
self.list.InsertStringItem(sys.maxint,i)
To find out if an item is checked use the following method of your listctrl
IsChecked(self, index)
which will return True/False for given index.