Is there a way to have the items of a Tkinter Listbox be Entry Widgets? The result would be that you could dynamically modify the text in an Listbox entry. If your Listbox looks like:
--------
| Apples |
| Pears |
| Oranges |
---------
then you would want to be able to click on Apples and write some arbitrary text - you could then bind the Enter key, say, to trigger a function based on the new text.
I know it has been a while since this question, but I have created a widget called 'ListboxEditable', which is able to act as a listbox and, when double-clicking on an item, the user can type anything inside an entry. Then, when the user clicks another row, the information is saved on the corresponding modified cell. Note that the user can use the up and down keys to browse the entire given list (the selected row has a different background color).
This code has been developed based on the answer from #Bryan Oakley.
Minimal working case
# Imports
from tkinter import *
from tkinter.ttk import *
# Import for the listboxEditable
from ListboxEditable import *
# Colors
colorActiveTab="#CCCCCC" # Color of the active tab
colorNoActiveTab="#EBEBEB" # Color of the no active tab
# Fonts
fontLabels='Calibri'
sizeLabels2=13
# Main window
root = Tk()
# *** Design *****
frame_name=Frame(root,bg=colorActiveTab) # Column frame
frame_name_label=Frame(frame_name,bg='blue') # Label frame
label_name=Label(frame_name_label, text="Header", bg='blue', fg='white', font=(fontLabels, sizeLabels2, 'bold'), pady=2, padx=2, width=10)
frame_name_listbox=Frame(frame_name,bg='blue') # Label frame
list_name=['test1','test2','test3']
listBox_name=ListboxEditable(frame_name_listbox,list_name)
# *** Packing ****
frame_name.pack(side=LEFT,fill=Y)
frame_name_label.pack(side=TOP, fill=X)
label_name.pack(side=LEFT,fill=X)
frame_name_listbox.pack(side=TOP, fill=X)
listBox_name.placeListBoxEditable()
# Infinite loop
root.mainloop()
ListboxEditable class
# Author: David Duran Perez
# Date: May 26, 2017
# Necessary imports
from tkinter import *
from tkinter import ttk
# Colors
colorActiveTab="#CCCCCC" # Color of the active tab
colorNoActiveTab="#EBEBEB" # Color of the no active tab
# Fonts
fontLabels='Calibri'
sizeLabels2=13
class ListboxEditable(object):
"""A class that emulates a listbox, but you can also edit a field"""
# Constructor
def __init__(self,frameMaster,list):
# *** Assign the first variables ***
# The frame that contains the ListboxEditable
self.frameMaster=frameMaster
# List of the initial items
self.list=list
# Number of initial rows at the moment
self.numberRows=len(self.list)
# *** Create the necessary labels ***
ind=1
for row in self.list:
# Get the name of the label
labelName='label'+str(ind)
# Create the variable
setattr(self, labelName, Label(self.frameMaster, text=self.list[ind-1], bg=colorActiveTab, fg='black', font=(fontLabels, sizeLabels2), pady=2, padx=2, width=10))
# ** Bind actions
# 1 left click - Change background
getattr(self, labelName).bind('<Button-1>',lambda event, a=labelName: self.changeBackground(a))
# Double click - Convert to entry
getattr(self, labelName).bind('<Double-1>',lambda event, a=ind: self.changeToEntry(a))
# Move up and down
getattr(self, labelName).bind("<Up>",lambda event, a=ind: self.up(a))
getattr(self, labelName).bind("<Down>",lambda event, a=ind: self.down(a))
# Increase the iterator
ind=ind+1
# Place
def placeListBoxEditable(self):
# Go row by row placing it
ind=1
for row in self.list:
# Get the name of the label
labelName='label'+str(ind)
# Place the variable
getattr(self, labelName).grid(row=ind-1,column=0)
# Increase the iterator
ind=ind+1
# Action to do when one click
def changeBackground(self,labelNameSelected):
# Ensure that all the remaining labels are deselected
ind=1
for row in self.list:
# Get the name of the label
labelName='label'+str(ind)
# Place the variable
getattr(self, labelName).configure(bg=colorActiveTab)
# Increase the iterator
ind=ind+1
# Change the background of the corresponding label
getattr(self, labelNameSelected).configure(bg=colorNoActiveTab)
# Set the focus for future bindings (moves)
getattr(self, labelNameSelected).focus_set()
# Function to do when up button pressed
def up(self, ind):
if ind==1: # Go to the last
# Get the name of the label
labelName='label'+str(self.numberRows)
else: # Normal
# Get the name of the label
labelName='label'+str(ind-1)
# Call the select
self.changeBackground(labelName)
# Function to do when down button pressed
def down(self, ind):
if ind==self.numberRows: # Go to the last
# Get the name of the label
labelName='label1'
else: # Normal
# Get the name of the label
labelName='label'+str(ind+1)
# Call the select
self.changeBackground(labelName)
# Action to do when double-click
def changeToEntry(self,ind):
# Variable of the current entry
self.entryVar=StringVar()
# Create the entry
#entryName='entry'+str(ind) # Name
self.entryActive=ttk.Entry(self.frameMaster, font=(fontLabels, sizeLabels2), textvariable=self.entryVar, width=10)
# Place it on the correct grid position
self.entryActive.grid(row=ind-1,column=0)
# Focus to the entry
self.entryActive.focus_set()
# Bind the action of focusOut
self.entryActive.bind("<FocusOut>",lambda event, a=ind: self.saveEntryValue(a))
# Action to do when focus out from the entry
def saveEntryValue(self,ind):
# Find the label to recover
labelName='label'+str(ind)
# Remove the entry from the screen
self.entryActive.grid_forget()
# Place it again
getattr(self, labelName).grid(row=ind-1,column=0)
# Change the name to the value of the entry
getattr(self, labelName).configure(text=self.entryVar.get())
Some sreenshots
No, tkinter doesn't support in-place editing of items in a listbox. Of course, if you don't really need a listbox, you can always stack labels or entry widgets on top of each other to get a similar effect.
you could give the user some entries then create a listbox from that input
but you cant just change a listboxes text like that
maybe try a different GUI Library like WX
EDIT
here is something you can do:
from Tkinter import *
root = Tk()
opt_list = ['opt1','opt2','opt3','opt4','opt5']
sel_list = []
def get_sel():
sel_list.append(Lb1.curselection())
root.destroy()
def change_opt():
entry = E.get()
change = entry.split(" ")
print change
Lb1.insert(int(change[0]),change[1])
root.update()
def cancel():
root.destroy()
E = Entry(root)
A = Button(root, text ="Change", command = change_opt)
B = Button(root, text ="Submit", command = get_sel)
C = Button(root, text ="Cancel", command = cancel)
Lb1 = Listbox(root, selectmode=MULTIPLE)
for i,j in enumerate(opt_list):
Lb1.insert(i,j)
Lb1.pack()
B.pack()
C.pack()
E.pack()
A.pack()
root.mainloop()
this will make a listbox with the options in opt_list then when you type for example 5 hello the entry and press Change it will add the option hello to the fifth place
thats the only way i can think of
import tkinter as tk
root=tk.Tk()
# root.geometry('300x240')
sb = tk.Scrollbar(root)
sb.pack(side=tk.RIGHT,fill=tk.Y)
E1 = tk.Entry(root)
E1.pack()
mylist = [*range(15)]
v = tk.StringVar(value=mylist)
b1=tk.Listbox(root,activestyle='dotbox',yscrollcommand=sb.set,listvariable=v,selectmode='SINGLE')
sb.config(command=b1.yview)
# for i in range(1,15):
# b1.insert(tk.END,i)
b1.pack()
def isfloat(s):
try:
return float(s)<float('inf')
except:
return False
def isInt(s):
try:
return int(s)<float('inf')
except:
return False
def set_entry_text(text):
E1.delete(0,tk.END)
E1.insert(0,text)
def set_item(event):
text = E1.get()
E1.delete(0,tk.END)
index = b1.curselection()[0]
b1.delete(index)
b1.insert(index,text)
print(v.get())
def set_item1(event):
text = E1.get()
E1.delete(0,tk.END)
index = b1.curselection()[0]
if isInt(text):
mylist[index] = int(text)
elif isfloat(text):
mylist[index] = float(text)
else:
mylist[index] = text
v.set(mylist)
print(v.get())
def edit_item(event):
text = E1.selection_get()
# set_entry_text(text)
E1.focus()
b1.bind('<Double-1>', edit_item)
E1.bind('<Return>',set_item1)
root.mainloop()
Related
newWindow = Toplevel(app)
newWindow.geometry("400x400+580+190")
Label(newWindow, text="choose the food").pack()
choice = Listbox(newWindow)
choice.pack()
food_f = open("food.txt")
for line in food_f:
f = {}
(f['food'], f['unit'], f['kcal'], f['standard']) = line.split(";")
choice.insert(END, f['food'])
t = StringVar()
t.set(choice.curselection())
Label(newWindow,textvariable=t).pack()
I want the label to print out in real time what is selected in the list box.
But above code can't.
You can create a binding on the virtual event <<ListboxSelect>>, and from within the bound function you can get the selected item and update the label using the configure method.
For example, given a listbox named listbox and a label named label, you can update the label like this when the selection changes:
def update_label(event):
curselection = listbox.curselection()
if curselection:
data = listbox.get(curselection[0])
label.configure(text=data)
else:
label.configure(text="")
listbox.bind("<<ListboxSelect>>", update_label)
I want to create a program where the user can create different buttons with the click of the mouse, those buttons should be independent. With this logic, the user can create a checkbutton that works, change from green to red when is selected. My problem is that if the user click the mouse again, the checkbutton moves instead of creating a new checkbutton. Any suggestion how to do it?
from tkinter import *
root = Tk()
button1 = IntVar()
def color_checkbutton(): # define the colors of the checkbutton
if button1.get() == 1:
example_checkbutton.configure(bg='red')
else:
example_checkbutton.configure(bg='green')
example_checkbutton = Checkbutton(root, variable=button1, textvariable=button1, command=color_checkbutton)
def place_checkbutton_in_canvas(e): # order to insert the checkbutton
xx_and = e.x
yy_and = e.y
example_checkbutton.place(x=xx_and, y=yy_and)
root.bind('<Button-1>', place_checkbutton_in_canvas)
root.mainloop()
You do only have one example_checkbutton. Whenever you call the .place()method, this button is moved around.
If you want new ones, just create them as new Checkbox-widgets:
def place_checkbutton_in_canvas(e): # order to insert the checkbutton
if len(str(e.widget))<3: ## Don't place a new one if a checkbox was clicked
xx_and = e.x
yy_and = e.y
Checkbutton(root, variable=button1, textvariable=button1, command=color_checkbutton).place(x=xx_and, y=yy_and)
This creates new checkbuttons which are all linked to the button1 variable.
EDIT:
If you want new checkbuttons, you'll have to maintain a list of IntVar() and Checkbutton() objects which is getting longer with each click. The code below should work. I also execute the color change upon creation to create them green and red.
from tkinter import *
root = Tk()
buttons = []
class CMD: #Auxilliary function for callbacks using parameters. Syntax: CMD(function, argument1, argument2, ...)
def __init__(s1, func, *args):
s1.func = func
s1.args = args
def __call__(s1, *args):
args = s1.args+args
s1.func(*args)
def color_checkbutton(pos=0): # define the colors of the checkbutton
if buttons[pos][0].get() == 1:
buttons[pos][2].configure(bg='red')
else:
buttons[pos][2].configure(bg='green')
def place_checkbutton_in_canvas(e): # order to insert the checkbutton
if len(str(e.widget))<3: ## Don't place a new one if a checkbox was clicked
b = IntVar()
pos = len(buttons)
xx_and = e.x
yy_and = e.y
buttons.append([b,pos, Checkbutton(root, variable=b, textvariable=b, command=CMD(color_checkbutton,pos))])
buttons[-1][2].place(x=xx_and, y=yy_and)
color_checkbutton(pos)
root.bind('<Button-1>', place_checkbutton_in_canvas)
root.mainloop()
I am trying to create a program that allows the user to select any number of check boxes and hit a button to return a random result from those check boxes. Since I am basing my list off the roster of Smash bros ultimate, I am trying to avoid creating 70+ variables just to place check boxes. However, I am unable to figure out how to iterate this. The various values set for rows are just placeholders until I can figure this out. I would also like to have a reset button at the top that allows the user to automatically uncheck every box. This code is what I have so far. Any help would be greatly appreciated.
#!/usr/bin/python3
from tkinter import *
window = Tk()
#window name and header
window.title("Custom Random SSBU")
lbl = Label(window, text="Select the fighters you would like to include:")
lbl.grid(column=1, row=0)
f = [] #check boxes
ft = open("Fighters.txt").readlines() #list of all the character names
fv=[0]*78 #list for tracking what boxes are checked
ff=[] #list to place final character strings
def reset():
for i in fv:
fv[i]=0
rst = Button(window, text="Reset", command=reset)
rst.grid(column=0, row=3)
for y in range (0,77):
f[y] = Checkbutton(window, text = ft[y], variable = fv[y])
f[y].grid(column=0, row=4+y)
def done():
for j in fv:
if fv[j] == 1:
ff.append(fv[j])
result = random.choice(ff)
r=Label(window, text=result)
d = Button(window, text="Done", command=done)
d.grid(column=0, row = 80)
window.mainloop()
Unfortunately I'm afraid you are going to have to create variables for each checkbox.
tkinter has special purpose Variable Classes for holding different types of values, and if you specify an instance of one as the variable= option when you create widgets like Checkbutton, it will automatically set or reset its value whenever the user changes it, so all your program has to do is check its current value by calling its get() method.
Here's an example of the modifications to your code needed to create them in a loop (and use them in the done() callback function):
import random
from tkinter import *
window = Tk()
#window name and header
window.title("Custom Random SSBU")
lbl = Label(window, text="Select the fighters you would like to include:")
lbl.grid(column=1, row=0)
with open("Fighters.txt") as fighters:
ft = fighters.read().splitlines() # List of all the character names.
fv = [BooleanVar(value=False) for _ in ft] # List to track which boxes are checked.
ff = [] # List to place final character strings.
def reset():
for var in fv:
var.set(False)
rst = Button(window, text="Reset", command=reset)
rst.grid(column=0, row=3)
for i, (name, var) in enumerate(zip(ft, fv)):
chk_btn = Checkbutton(window, text=name, variable=var)
chk_btn.grid(column=0, row=i+4, sticky=W)
def done():
global ff
ff = [name for name, var in zip(ft, fv) if var.get()] # List of checked names.
# Randomly select one of them.
choice.configure(text=random.choice(ff) if ff else "None")
d = Button(window, text="Done", command=done)
d.grid(column=0, row=len(ft)+4)
choice = Label(window, text="None")
choice.grid(column=1, row=3)
window.mainloop()
I wasn't sure where you wanted the Label containing the result to go, so I just put it to the right of the Reset button.
variable = fv[y]
This looks up the value of fv[y] - i.e, the integer 0 - at the time the Checkbutton is created, and uses that for the variable argument.
You need to use an instance of one of the value-tracking classes provided by TKinter, instead. In this case we want BooleanVar since we are tracking a boolean state. We can still create these in a list ahead of time:
text = open("Fighters.txt").readlines()
# Let's not hard-code the number of lines - we'll find it out automatically,
# and just make one for each line.
trackers = [BooleanVar() for line in text]
# And we'll iterate over those pair-wise to make the buttons:
buttons = [
Checkbutton(window, text = line, variable = tracker)
for line, tracker in zip(text, trackers)
]
(but we can not do, for example trackers = [BooleanVar()] * len(text), because that gives us the same tracker 78 times, and thus every checkbox will share that tracker; we need to track each separately.)
When you click the checkbox, TKinter will automatically update the internal state of the corresponding BooleanVar(), which we can check using its .get() method. Also, when we set up our options for random.choice, we want to choose the corresponding text for the button, not the tracker. We can do this with the zip trick again.
So we want something more like:
result_label = Label(window) # create it ahead of time
def done():
result_label.text = random.choice(
label
for label, tracker in zip(text, trackers)
if tracker.get()
)
I need to represent in "ventana2" the pairs entered in "ventana", so that a new frame appears when the key is new. When the key already exists in the dictionary, I need to change the old value in the frame created for that key previously (the new value is adding old and new).
I can not get the frames permanently related to my dictionary partner, through the key.
Thank you very much in advance, and sorry for my english.
Here is a summary of the code:
import tkinter as tk
ventana = tk.Tk()
ventana2 = tk.Tk()
name = tk.StringVar()
tk.Entry(ventana, textvariable=name, width=30).grid(row=0, column=1)
tk.Label(ventana, text = 'Nombre').grid(row=0, column=0)
value = tk.StringVar()
tk.Entry(ventana, textvariable=value, width=30).grid(row=1, column=1)
tk.Label(ventana, text = 'Celular').grid(row=1, column=0)
contactos={}
def intro():
nom = name.get()
if nom in contactos:
cel = contactos[nom] + float(value.get())
contactos[nom] = cel
else:
cel = float(value.get())
contactos[nom] = cel
create_widget()
def create_widget():
frame = tk.Frame(ventana2)
frame.pack()
nomb = tk.Label(frame, text=name.get()).pack(side=tk.LEFT)
telf = tk.Label(frame, text=contactos[name.get()]).pack(side=tk.RIGHT)
intro_btn = tk.Button(ventana, text='Intro', command = intro)
intro_btn.grid(row=2, column=0, columnspan=2, sticky = 'ew')
ventana.mainloop()
Labels created inside the create_widget() function is in the function scope. After the function ends all references to the label is lost. So you need to think of a way to save references to the label (suggest return statement) and associate them to the dictionary of contactos.
Update - relate a frame with a value
Save a reference to the object you wish to remember and the name you want to use to recall it in a list(or dict or tuple et.). Then append all that to your global list of widgets. For example:
nomb = tk.Label( ... )
widget_parameters = ['Nomb Label', nomb]
global_widget_list.append(widget_parameters)
Then you can search the global_widget_list for any widget you have named and get a referance to that widget.
I have included some example code to illustrate one way that you can accomplish that. Play around with it until you understand it and you will be able to implement it in your own application.
from tkinter import *
import time
root = Tk()
root.geometry('300x200')
global_widget_list = [] # List for holding all widgets
def make_label(): # Create label
text_label = Label(root,text='Text input')
text_label.pack()
global_widget_list.append(['Text Label',text_label]) # Add widget to list
def make_input(): # Create entry
inputvar = StringVar()
text_input = Entry(root,width=20,textvariable=inputvar)
text_input.pack()
global_widget_list.append(['Text Input',text_input,inputvar]) # Add widget to list
make_label() # Run functions to cretae GUI
make_input()
root.update() # Take care of updating GUI
time.sleep(3) # Wait so you have time to see the original, then change it
# Now, loop through all widgets and do what you want
for widget in global_widget_list:
widget_name = widget[0]
widget_id = widget[1]
print(widget_name, 'has identity', widget_id)
if widget_name == 'Text Label':
print('Changing test label text to: ALL CAPS')
widget_id.configure(text='ALL CAPS')
if widget_name == 'Text Input':
print('Changing text in entry to: SAMPLE')
var = widget[2]
var.set('SAMPLE')
root.update() # Take care of updating GUI
time.sleep(3) # Wait so you have time to see the changes, then change it
print('Removing Entry from application GUI')
global_widget_list[1][1].pack_forget() # Remove entry form GUI
I'm tring to put some drop down list on a graphic interface I'm building.
I've found the following code for a drop down list, but I'm not able to adapt it to my code.
from Tkinter import *
def print_it(event):
print var.get()
root = Tk()
var = StringVar()
var.set("a")
OptionMenu(root, var, "a","b","c", command=print_it).pack()
root.mainloop()
This is my code, it's quite simple what I've done so far. A menu shows up, it asks for how many (n) components does the users want to enter, and it shows n options to entry. The code above shows 'blank' entrys after you put the desired number of components. I want to replace those three blank entrys with three drop down list.
It's marked when I want to put those dropdown lists.
from Tkinter import *
import Image
import ImageTk
import tkFileDialog
class Planificador:
def __init__(self,master):
master.title("Planificador")
self.frameOne = Frame(master)
self.frameOne.grid(row=0,column=0)
# Logo
self.imgLabel = Label(self.frameOne, image = None)
self.imgLabel.grid(row=0,column=0)
self.img = ImageTk.PhotoImage(file = "logo.png")
self.imgLabel["image"] = self.img
self.botones()
def botones(self):
self.piezastext = Label(self.frameOne, text = " number of components ", justify="center")
self.piezastext.grid(row=1, column=0)
self.entrypiezas = Entry(self.frameOne,width=5)
self.entrypiezas.grid(row=2, column=0)
self.aceptarnumpiezas = Button(self.frameOne,text="Aceptar", command=self.aceptar_piezas,width=8)
self.aceptarnumpiezas.grid(row=6, column=0)
def aceptar_piezas(self):
num_piezas = self.entrypiezas.get()
print num_piezas
self.piezastext.grid_remove()
self.entrypiezas.grid_remove()
self.aceptarnumpiezas.grid_remove()
n = 1;
while n <= int(num_piezas):
self.textopieza = Label(self.frameOne, text = "Pieza", justify="left")
self.textopieza.grid(row=n, column=0)
// INSTEAD THESE 'n' BLANK ENTRYS, I WANT TO PUT 'n' DROP DOWN LISTS
self.entrypiezas = Entry(self.frameOne,width=5)
self.entrypiezas.grid(row=n, column=1)
self.aceptarpiezas = Button(self.frameOne,text="Aceptar",width=8)
self.aceptarpiezas.grid(row=int(num_piezas)+1, column=0)
n += 1
# Main
if __name__ == "__main__":
# create interfacE
root = Tk()
movieApp = Planificador(root)
root.mainloop()
So I want to know how can I put that drop down list on a given frame, frameOnein my case, instead of a full window. Thanks in advance.
I modified your aceptar_piezas function to do what I think you want:
def aceptar_piezas(self):
num_piezas = self.entrypiezas.get()
print num_piezas
self.piezastext.grid_remove()
self.entrypiezas.grid_remove()
self.aceptarnumpiezas.grid_remove()
# Create a list of tuples to hold the dynamically created Optionmenus
# The first item in the tuple is the menu, the second is its variable
self.optionmenus = list()
n = 1
while n <= int(num_piezas):
self.textopieza = Label(self.frameOne, text = "Pieza", justify="left")
self.textopieza.grid(row=n, column=0)
# Variable for the Optionmenu
var = StringVar()
# The menu
menu = OptionMenu(self.frameOne, var, "a","b","c")
menu.grid(row=n, column=1)
# Set the variable to "a" as default
var.set("a")
# Add the menu to the list of Optionmenus
self.optionmenus.append((menu, var))
n += 1
def clicked():
"""This function was made just to demonstrate. It is hooked up to the button"""
for optionmenu in self.optionmenus:
print optionmenu[1].get()
print self.optionmenus
# This button doesn't need to be in the while loop
self.aceptarpiezas = Button(self.frameOne, text="Aceptar", command=clicked, width=8)
self.aceptarpiezas.grid(row=int(num_piezas)+1, column=0)
The tuples in the list are in the order that the Optionmenus were created. So, the first tuple contains the data for the first Optionmenu, the second for the second, and so forth.