Here is a much simplified version of what I was trying to do.
import Tkinter as tk
root = tk.Tk()
n = 1
def show1():
print var.get()
def add1():
global n
l = 'Option %d' % n
n += 1
op['menu'].add_command(label=l,command=tk._setit(var,l))
var.set(l)
print 'added %s' % l
var = tk.StringVar()
op = tk.OptionMenu(root,var,[], command=show1)
op.pack()
tk.Button(root,text='add 1', command=add1).pack()
tk.Button(root,text='show', command=show1).pack()
root.mainloop()
The 'add 1' button successfully adds options to the option menu.
Clicking on an option does not call the show1 routine, you have to click on the 'show' button.
-------Original Question-----
I'm trying to read in a number of selected files and save information about each of them.
As I read them in the file base name is stored in the option list. That seems to be working.
I would like to show the saved information when I click on a selection in the option menu. That is not working.
The code below is adding name to the option list, but you have to click the 'Get it' button to show the data.
#!/usr/bin/python2.7
import Tkinter as tk
import os,sys
import tkFileDialog as tkfd
class E(tk.Frame):
def __init__(self):
tk.Frame.__init__(self)
self.grid()
self.files = {}
self.statusMsg = tk.StringVar()
self.nLines = tk.StringVar()
self.maxLine = tk.StringVar()
self.fileName = tk.StringVar()
tk.Button(self,text='Get a file',command=self.openfile, bd=5).grid(row=1, column=0)
self.fileOption = tk.OptionMenu(self,self.fileName, [], command=self.getIt)
self.fileOption.configure(width=10, bd=5, relief='ridge')
self.fileOption.grid(row=2, column=0)
tk.Label(self,text='Line Count').grid(row=3, column=0)
tk.Label(self,textvariable=self.nLines).grid(row=3, column = 1)
tk.Label(self,text='Max Line').grid(row=4, column=0)
tk.Label(self,textvariable=self.maxLine).grid(row=4, column = 1)
tk.Button(self,text='show file',command=self.getIt, bd=5).grid(row=5)
tk.Label(self,text='Status').grid(row=6, column=0)
tk.Label(self,textvariable=self.statusMsg,width=20).grid(row=6, column = 1)
def openfile(self):
textFile = tkfd.askopenfile(mode='r', defaultextension='.txt',
filetypes=[("text","*.txt"),("All Files","*")],
initialdir='.')
(fileBaseName, fileExt) = os.path.splitext(os.path.basename(textFile.name))
maxLength = -1
lineCount = 0
for line in textFile:
lineCount += 1
maxLength = max(maxLength,len(line))
self.files[fileBaseName] = [maxLength,lineCount]
self.nLines.set(lineCount)
self.maxLine.set(maxLength)
self.statusMsg.set('Opened %s' % fileBaseName)
""" This works to add the file but the command is not
executed when selected in the optionmenu """
self.fileOption['menu'].add_command(label=fileBaseName, command=tk._setit(self.fileName,fileBaseName))
self.fileName.set(fileBaseName)
"""
fileList = sorted(self.files.keys())
for fname in fileList:
self.fileOption['menu'].add_command(label=fname, command=lambda v=fileList: self.getIt)
"""
"""
self.fileOption = tk.OptionMenu(self,self.fileName, fileList, command=self.getIt)
print fileList
"""
"""
self.fileOption['menu'].add_command(label=fileBaseName, command=tk._setit(self.fileName,fileBaseName))
self.fileOption.configure(command=self.getIt)
"""
"""
self.fileOption['menu'].add_command(label=fileBaseName, command=self.getIt)
"""
self.fileName.set(fileBaseName)
def getIt(self):
[maxLength,lineCount] = self.files[self.fileName.get()]
self.nLines.set(lineCount)
self.maxLine.set(maxLength)
self.statusMsg.set('got it')
if __name__ == "__main__":
app = E()
#app.title('Build Roof')
app.mainloop()
The comments show other things I've tried.
There are numerous examples of adding items to the option list and others that set the command, but none that do both.
P.S. I'd like to get rid of the pesky first blank entry in the option list
The solution turned out to be pretty simple. It works with a grid layout. Just leave an empty space where the OptionMenu needs to go and append new entries to a list. Then create a new OptionMenu as you add entries.
The OptionMenu doesn't even appear until you have at least one entry.
import Tkinter as tk
root = tk.Tk()
n = 1
vars=[]
def show1(*entry):
print var.get()
def add1():
global n
l = 'Option %d' % n
n += 1
vars.append(l)
op = tk.OptionMenu(root,var,*vars, command=show1).grid(row=0, column=1)
var.set(l)
print 'added %s' % l
var = tk.StringVar()
root.grid()
tk.Button(root,text='add 1', command=add1).grid(row=0, column=0)
tk.Label(root,text=' ', width=12).grid(row=0,column=1)
The Label in the last line doesn't need to be there if you have enough other things in the grid to keep the space open
Related
I tried to create a multiple checkboxes and get the information whether they are checked or not. I tried to use tkinter for this purpose. The number of checkboxes would be variable. Up to now, I found a way to create the checkboxes with the following code. With this, 10 checkboxes are created at which people can tick any of them
class Example(tk.Frame):
def __init__(self, root, *args, **kwargs):
tk.Frame.__init__(self, root, *args, **kwargs)
self.root = root
self.vsb = tk.Scrollbar(self, orient="vertical")
self.text = tk.Text(self, width=40, height=20,
yscrollcommand=self.vsb.set)
self.vsb.config(command=self.text.yview)
self.vsb.pack(side="right", fill="y")
self.text.pack(side="left", fill="both", expand=True)
n=10
for i in range(n):
cb = tk.Checkbutton(self, text="Modul %s" % i)
self.text.window_create("end", window=cb)
self.text.insert("end", "\n")
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(side="top", fill="both", expand=True)
root.mainloop()
However, the information are not saved in any variable. If I add variable to be dumped in the cb, the code will check every checkboxes. The edited code section is as follow (sorry that I couldn't highlight the addition):
class Example(tk.Frame):
def __init__(self, root, *args, **kwargs):
tk.Frame.__init__(self, root, *args, **kwargs)
self.root = root
self.vsb = tk.Scrollbar(self, orient="vertical")
self.text = tk.Text(self, width=40, height=20,
yscrollcommand=self.vsb.set)
self.vsb.config(command=self.text.yview)
self.vsb.pack(side="right", fill="y")
self.text.pack(side="left", fill="both", expand=True)
n=10
var1 = IntVar()
val =[]
for i in range(n):
cb = tk.Checkbutton(self, text="Modul %s" % i, variable=var1)
self.text.window_create("end", window=cb)
self.text.insert("end", "\n") # to force one checkbox per line
val.append(var1.get())
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(side="top", fill="both", expand=True)
root.mainloop()
Could you help what can I add to the code in order to be able to get the checked Modules by the user? for instance I will get in "val" variable a list with [1, 0, 1, 0, 0, 0, 1, 0, 0, 0] if somebody tick module 0, 2, and 6
I look forward for your feedback.
Are you looking for something like this?
import tkinter as tk
def done():
result = []
for var in variables:
result.append(var.get())
print(result)
root = tk.Tk()
variables = []
check_buttons = []
for i in range(10):
var = tk.IntVar(root)
check_button = tk.Checkbutton(root, text="Modul %i" % i, variable=var)
check_button.pack()
variables.append(var)
check_buttons.append(check_button)
done_button = tk.Button(root, text="Done", command=done)
done_button.pack()
root.mainloop()
I created 10 variables in a list called variables and connected them to each Checkbutton
This is quite simple, the mistake is you are creating one IntVar for all the checkbuttons, what you should be having is different IntVar for different buttons. Then what I want to add is, instead of val being the values from IntVar let it be the IntVar themselves, so later it can be reused. Here I am using bind to print the list, you can create a button and add command option to it.
self.val = [] # self.val if you want to access it outside __init__, or just val
for i in range(n):
var1 = IntVar()
cb = tk.Checkbutton(self, text="Modul %s" % i, variable=var1)
self.text.window_create("end", window=cb)
self.text.insert("end", "\n") # to force one checkbox per line
self.val.append(var1)
self.text.bind('<Return>',lambda e:print([x.get() for x in self.val])) # Dummy function to just print a new list
What is [x.get() for x in self.val] ? It is simple List Comprehension which means:
temp = [] # Any empty list
for x in self.val:
temp.append(x.get())
Here is another way of doing (tho probably other answers will better suit You depending on what You know):
from tkinter import Tk, Checkbutton, IntVar
from functools import partial
def func(n):
print(f'Selected {n + 1}') if variables[n].get() == 1 else print(f'Deselected {n + 1}')
variables = []
root = Tk()
for i in range(10):
variables.append(IntVar())
Checkbutton(root, text=f'Option {i + 1}', variable=variables[i], command=partial(func, i)).pack()
root.mainloop()
(By suggestion #CoolCloud You can replace the shown command with this: command=lambda i=i: func(i), that should also work, also then You don't have to import functools)
However this is a pretty compact setup.
Explanation:
First there is an empty list, where all the Checkbox variables will be stored.
Then in range 10 which means that 10 Checkboxes will be created we do the following:
First we append a variable to the list that will get assigned to each Checkbutton
Then it creates a Checkbutton and adds to it the variable by using indexing and immediately packs it.
About that command:
The partial basically makes it so that the function given in its argument will always get executed with that variable. More about that here
func() function:
print number of option when selected, otherwise print the number when deselected (adding the correct 'selected: no' and 'deselected: no'). It can also be written as:
if all_checkboxes[n][0].get() == 1:
print(f'Selected {n + 1}')
else:
print(f'Deselected {n + 1}')
Hope this helps, if You have any questions ask them.
Source for information about Checkbox and its attributes and arguments.
I am creating a GUI, where I have placed three buttons for selecting a file. When I click the button it browse for a file and display the selected file path and I am trying to do it with a single browse function since the operation is same. I am bit confused to how I should proceed . Can anyone please help me out.
Thanks in advance.
Here is my code:
Browse_Files.py
from tkinter import filedialog
def Browse_File():
global Bfilepath
Bfilepath = filedialog.askopenfilename(filetypes = (("Please select the required file", "*"), ("All files", "*")))
return Bfilepath
Main.py
from tkinter import *
import sys
import fileinput
import Browse_Files
root = Tk()
root.geometry('1400x800')
root.title('Dr Configuration')
Heading = Label(root, font=('Times New Roman',50,'bold'),text = "Arxml
Configuration Tool").place(x=300,y=25)
BasepathLabel = Label(root,font=('Times New Roman',20,'bold'),text = " Base
arxml").place(x=200,y=150)
NewpathLabel= Label(root,font=('Times New Roman',20,'bold'),text = "
New/Unedited arxml").place(x=200,y=250)
InterfaceLabel = Label(root,font=('Times New Roman',20,'bold'),text = "
Interface_File").place(x=200,y=350)
BpathtoDisp = StringVar(None)
BpathEntry = Entry(root,font=('Times New Roman',18),textvariable=
BpathtoDisp,justify='left',width=48).place(x=500,y=150)
NpathtoDisp = StringVar(None)
NpathEntry = Entry(root,font=('Times New Roman',18),textvariable=
NpathtoDisp,justify='left',width=48).place(x=500,y=250)
InterPathtoDisp = StringVar(None)
InterPathEntry = Entry(root,font=('Times New Roman',18),textvariable=
NpathtoDisp,justify='left',width=48).place(x=500,y=350)
button1 = Button(root,text="...",height=1,width=3,command=lambda:Browse_Files.Browse_File()).place(x=1100,y=150)
button2 = Button(root,text="...",height=1,width=3,command=lambda:Browse_Files.Browse_File()).place(x=1100,y=250)
button3 = Button(root,text="...",height=1,width=3,command=lambda:Browse_Files.Browse_File()).place(x=1100,y=350)
root.mainloop()
You could create a class that contains the functionality to have a button, open a file dialog, store it and make it available to other parts of the program.
I have a similar widget that I use in many different programs
from tkinter import *
from tkinter import filedialog
class FileSelect(Frame):
def __init__(self,master,label="",**kw):
Frame.__init__(self,master)
self.configure(**kw)
self.file = StringVar()
self.Label = Label(self, text=label)
self.Label.config(width=10,anchor=E)
self.filenamebox = Entry(self,text=self.file)
self.filenamebox.config(width=50)
self.btnBrowse = Button(self,text='Browse',command=self.browse_file)
self.btnBrowse.config(width=10)
self.Label.grid(row=0,column=0,pady=5,sticky=E)
self.filenamebox.grid(row=0,column=1,pady=5)
self.btnBrowse.grid(row=0,column=2,pady=5,padx=5)
def browse_file(self):
filename = filedialog.askopenfilename(filetypes=[('All File','*.*')])
self.file.set(filename)
def get_filename(self):
return self.file.get()
def main():
root = Tk()
root.title("Example Widget")
fileSelect1 = FileSelect(root,label="My File 1")
fileSelect1.grid()
fileSelect2 = FileSelect(root,label="My File 2")
fileSelect2.grid()
root.mainloop()
if __name__ == '__main__':
main()
In your code if you want the value of the file selected use
fileSelect1.get_filename()
EDIT: I've created a new version that is only a Button 'with memory' to remember which item was selected by the file dialog. This will allow you to place using the place geometry manager (which I don't recommend). Its not complete but you should get the idea.
from tkinter import *
from tkinter import filedialog
class FileSelectButton(Button):
def __init__(self,master,**kw):
Button.__init__(self,master,text='Browse',command=self.browse_file,width=10,**kw)
self.file = StringVar()
def browse_file(self):
filename = filedialog.askopenfilename(filetypes=[('All File','*.*')])
self.file.set(filename)
def get_filename(self):
return self.file.get()
def main():
root = Tk()
root.geometry('1400x800')
root.title("Example Widget")
Label(root, font=('Times New Roman',50,'bold'),text = "Label1").place(x=200,y=150)
fileSelect1 = FileSelectButton(root)
fileSelect1.place(x=500,y=150)
Label(root, font=('Times New Roman',50,'bold'),text = "Label2").place(x=200,y=250)
fileSelect2 = FileSelectButton(root)
fileSelect2.place(x=500,y=250)
root.mainloop()
if __name__ == '__main__':
main()
I am new to programming in tkinter and am very stuck on using checkbuttons. I have created multiple checkbuttons in one go, all with different text for each one and a different grid position. However I have no idea how to get the value of each button or how to even set it. I want to be able to get the state/value for each button and if it is checked, then another function is called. How do I set and call the value/state of each button? Can this be done in a for loop or do I have to create them individually?
def CheckIfValid(self, window):
Class = self.ClassChosen.get()
Unit = self.UnitChosen.get()
Topic = self.TopicChosen.get()
if Class == '' or Unit == '' or Topic == '':
tm.showinfo("Error", "Please fill in all boxes")
else:
QuestionData = OpenFile()
QuestionsList = []
for x in range (len(QuestionData)):
#if QuestionData[x][2] == Topic:
QuestionsList.append(QuestionData[x][0])
for y in range(len(QuestionsList)):
self.ButtonVal[y] = IntVar()
Checkbutton(window, text = QuestionsList[y], padx = 20, variable = self.ButtonVal[y]).grid(row = 12 + y, column = 2)
ConfirmSelection = Button(window, text = "Set Homework", command = lambda: SetHomeworkClass.ConfirmHomework(self)).grid()
print(variable.get()) #here I would like to be able to get the value of all checkbuttons but don't know how
You use the list of IntVars either called from a command= in the Checkbutton or in the Button. Don't know why you are calling another class's object, SetHomeworkClass.objectConfirmHomework(self). It doesn't look like that will work as you have it programmed, as that is another name space and the list of IntVars is in this name space, but that is another topic for another thread.
try:
import Tkinter as tk # Python2
except ImportError:
import tkinter as tk # Python3
def cb_checked():
# remove text from label
label['text'] = ''
for ctr, int_var in enumerate(cb_intvar):
if int_var.get(): ## IntVar not zero==checked
label['text'] += '%s is checked' % cb_list[ctr] + '\n'
root = tk.Tk()
cb_list = [
'apple',
'orange',
'banana',
'pear',
'apricot'
]
# list of IntVar for each button
cb_intvar = []
for this_row, text in enumerate(cb_list):
cb_intvar.append(tk.IntVar())
tk.Checkbutton(root, text=text, variable=cb_intvar[-1],
command=cb_checked).grid(row=this_row,
column=0, sticky='w')
label = tk.Label(root, width=20)
label.grid(row=20, column=0, sticky='w')
# you can preset check buttons (1=checked, 0=unchecked)
cb_intvar[3].set(1)
# show what is initially checked
cb_checked()
root.mainloop()
I am currently trying to insert data from an external file which I have defined with the function "browse" as shown below, and these data to implement inside the Listboxes which I have divided in 3 parts, the data in the external file is simply some dates and numbers which I will show below.
Could anyone help me figure out how do I implement data inside a Listbox as shown in the pictures below. P.S datesel() function is date selection to pick up dates manually after implementing the file inside of the listbox in which I am struggling to solve. Lastly Date Listboxes must be only integer as show in the picture 2.Data file link
Current results in 1st picture
Results that I need 2nd picture
Data file picture #3 that I implement through Button 1
from Tkinter import *
import tkFont , time
import ttk,csv,sys,os
import Tkinter,tkFileDialog
class Application(Frame):
def __init__(self,root):
Frame.__init__(self,root)
self.root=root
self.function1()
self.function2()
def function1(self): #tell the machine we are having new widget
self.frame1 = Frame(self.root)
self.frame3 = Frame(self.root, bg="lightblue", borderwidth=2, relief=GROOVE)
self.label1 = Label(self.frame1, text="Upload Acitivity File:")
self.first_button = Button(self.frame1, text="Button 1",command=self.browse)
#Start date selector
self.Sdate = Label(self.frame3, text="Start Date(dd/mm/yy): ")
self.Slb = Listbox(self.frame3, width = 6,height = 8,selectmode='multiple',exportselection=0)
self.Slb2 = Listbox(self.frame3, width=6, height=8,selectmode='multiple',exportselection=0)
self.Slb3 = Listbox(self.frame3, width=6, height=8,selectmode='multiple',exportselection=0)
def function2(self): # # tell the machine where our widget will be
self.frame1.pack()
self.frame3.pack()
self.label1.pack(padx=5, pady=10, side=LEFT)
self.first_button.pack(side=LEFT)
#start and end date
self.Sdate.grid(row =0,column=0)
self.Slb.grid(row =0,column=1)
self.Slb2.grid(row=0, column=2)
self.Slb3.grid(row=0, column=3)
def browse(self):
file = tkFileDialog.askopenfile(mode='rb', title='Choose a file')
self.data = csv.reader(file)
self.datalist = []
for row in self.data:
if len(row) != 0:
self.datalist = self.datalist + [row]
self.datalist.sort()
print self.datalist
def datesel(self):
# get selected line index
self.index = self.Slb.curselection()[0]
# get the line's text
self.seltext = self.Slb.get(self.index)
print self.seltext
self.index2 = self.Slb2.curselection()[0]
self.seltext2 = self.Slb2.get(self.index2)
print self.seltext2
self.index3 = self.Slb3.curselection()[0]
self.seltext3 = self.Slb3.get(self.index3)
print self.seltext3
self.Slist = [self.seltext,self.seltext2,self.seltext3]
self.Slist.sort(0,END)
print self.Slist
def main():
parent=Tk() # main frame
parent.geometry('600x600+300+30') #The height and width of the program
parent.title('Motion Tracker')#assign the title of the program
app = Application(parent)
parent.mainloop()#keeps the program running for infinite amount of time
main()
I don't understand why you want the day, month, and year in separate Listboxes, but anyway, here's some code that shows how to fill 3 Listboxes in the way your 2nd picture shows. I've reduced the code to the bare minimum, and I've hard-coded the filename into the class, but that's easy to fix.
import Tkinter as tk
class Application(tk.Frame):
def __init__(self, root):
tk.Frame.__init__(self, root)
self.pack()
self.root = root
self.do_listboxes()
def do_listboxes(self):
tk.Button(self, text="Get dates", command=self.fill_dates).pack()
self.Slb1 = tk.Listbox(self, width=6, height=8, selectmode='multiple', exportselection=0)
self.Slb2 = tk.Listbox(self, width=6, height=8, selectmode='multiple', exportselection=0)
self.Slb3 = tk.Listbox(self, width=6, height=8, selectmode='multiple', exportselection=0)
self.Slb1.pack(side=tk.LEFT)
self.Slb2.pack(side=tk.LEFT)
self.Slb3.pack(side=tk.LEFT)
def fill_dates(self):
fname = 'dkebz.txt'
# Use sets to get rid of duplicated days, months, and years
days, mons, yrs = set(), set(), set()
with open(fname, 'r') as f:
#Skip header
next(f)
for row in f:
# Extract the date from the row
date = row.split(',')[1]
# Extract the day, month, and year from the date
day, mon, yr = date.split('/')
days.add(day)
mons.add(mon)
yrs.add(yr)
# Populate the list boxes
for day in sorted(days):
self.Slb1.insert(tk.END, day)
for mon in sorted(mons):
self.Slb2.insert(tk.END, mon)
for yr in sorted(yrs):
self.Slb3.insert(tk.END, yr)
def main():
parent = tk.Tk()
parent.title('Motion Tracker')
app = Application(parent)
parent.mainloop()
main()
I've used import Tkinter as tk rather than from Tkinter import *. The "star" import dumps 175 Tkinter names into your namespace (in Python 3, 136 names), which is messy and can cause name collisions, especially if you do other "star" imports. Using import Tkinter as tk means that you have to prefix each Tkinter name with tk., so it involves a little more typing, but it makes the code easier to read because it's clear where each name comes from.
For that, you just need to modify the browse method. I have hard-coded the data to reflect what your file image showed. So if the data is exactly what you provided, this works. If it works for you, uncomment the 2 lines I commented, and delete the self.data list definition I wrote.
def browse(self):
file = tkFileDialog.askopenfile(title='Choose a file')
try:
with open(file, 'r') as reader:
self.data = list(reader)
except:
raise
self.datalist = []
for row in self.data:
if len(row) != 0 and not row.startswith('Activity'):
self.datalist = self.datalist + [row]
activity, date, steps = row.split(',')
month, day, year = date.split('/')
self.Slb.insert(END, month)
self.Slb2.insert(END, day)
self.Slb3.insert(END, year)
This is the same problem I posed earlier today and which a couple of you tried to help me with, but I can't get it to work. All I want to do is to populate "ichose" with the multiple selections I make when I click on the listbox.
import Tkinter as tk
from Tkinter import *
global ichose
class App(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self,master)
self.master=master
self.grid()
self.ichose = ()
self.l = Listbox(self, height=10, selectmode=EXTENDED)
# Selectmode can be SINGLE, BROWSE, MULTIPLE or EXTENDED. Default BROWSE
self.l.grid(column=0, row=0, sticky=(N,W,E,S))
self.l.bind("Double-Button-1", self.entered)
s = Scrollbar(self, orient=VERTICAL, command=self.l.yview)
s.grid(column=0, row=0, sticky=(N,S,E))
self.l['yscrollcommand'] = s.set
for i in range(1,101):
self.l.insert('end', 'Line %d of 100' % i)
def entered(self, event):
self.ichose = self.selection_get()
self.ichose = ('hello')
root=tk.Tk()
root.title('Listbox Problem')
root.geometry('200x200')
app=App(root)
root.mainloop()
print app.ichose
Whatever I do, "ichose" comes out as an empty tuple ().
It's clear that the function "entered" is never called because I never see the test string 'hello'.
I also don't know what the various options are as in "Double-Button-", "<>" etc. Where can I find a list and explanation of each one?
If somebody could please just modify my program so the "print ichose" works, I'd be really grateful. You can see from my program that I don't really know what I'm doing but am keen to learn. Thank you.
I've finally found the answer to my own question. This is REALLY useful if you want to capture multiple responses from a listbox. I've commented a lot. Hope it helps!
import Tkinter as tk
from Tkinter import *
class App(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self,master)
self.master=master
self.grid()
self.ichose = []
self.l = Listbox(self, height=10, selectmode=MULTIPLE)
# Selectmode can be SINGLE, BROWSE, MULTIPLE or EXTENDED. Default BROWSE
self.l.grid(column=0, row=0, sticky=(N,W,E,S))
s = Scrollbar(self, orient=VERTICAL, command=self.l.yview)
s.grid(column=0, row=0, sticky=(N,S,E))
self.l['yscrollcommand'] = s.set
for i in range(1,101):
self.l.insert('end', 'Line %d of 100' % i)
# Create Textbox that will display selected items from list
self.selected_list = Text(self,width=20,height=10,wrap=WORD)
self.selected_list.grid(row=12, column=0, sticky=W)
# Now execute the poll() function to capture selected list items
self.ichose = self.poll()
def poll(self):
items =[]
self.ichose = []
# Set up an automatically recurring event that repeats after 200 millisecs
self.selected_list.after(200, self.poll)
# curselection retrieves the selected items as a tuple of strings. These
# strings are the list indexes ('0' to whatever) of the items selected.
# map applies the function specified in the 1st parameter to every item
# from the 2nd parameter and returns a list of the results. So "items"
# is now a list of integers
items = map(int,self.l.curselection())
# For however many values there are in "items":
for i in range(len(items)):
# Use each number as an index and get from the listbox the actual
# text strings corresponding to each index, and append each to
# the list "ichose".
self.ichose.append(self.l.get(items[i]))
# Write ichose to the textbox to display it.
self.update_list()
return self.ichose
def update_list(self):
self.selected_list.delete(0.0, END)
self.selected_list.insert(0.0, self.ichose)
root=tk.Tk()
root.title('Listbox Multi-Capture')
root.geometry('200x340')
app=App(root)
root.mainloop()
print app.ichose
# ----------------[ Listbox EXAMPLE ]----------------
self.sarcCountries = (
"Bangladesh",
"India",
"Pakistan",
"Nepal",
"Bhutan",
"Sri Lanka",
"Afghanistan"
)
self.listData = StringVar(value = self.sarcCountries)
self.listbox = Listbox(
master = self,
height = 10,
listvariable = self.listData,
selectmode = MULTIPLE,
selectbackground = "#BC80CC"
)
self.listbox.bind("<<ListboxSelect>>", self.OnListboxSelectionChanged)
self.listbox.pack(fill = BOTH, expand = 0, padx = 10, pady = 10)
# ----------------[ Listbox EXAMPLE ]----------------
def OnListboxSelectionChanged(self, val):
# NOTE: If your listbox's select mode is MULTIPLE, then you may use this portion of code
selections = val.widget.curselection()
print("---------------------------")
if (selections != ()):
for index in selections:
print(self.sarcCountries[int(index)])
print("---------------------------")