Tkinter Combobox dynamically set values - python

I'm attempting to set the options of a Tkinter Combobox dynamically. My code almost works, and I'm not sure why.
The code is designed to allow typing a string into an Entry box. It then searches through a list for any items that contain that string. So for example, if you type
Mi
into the entry box the list becomes
['Mickey', 'Minnie']
All this works as expected.
The Combobox [values] attribute is supposed to update whenever <FocusIn> is triggered using a function. This does indeed happen, but only after I click on the Combobox twice. I'm not sure why clicking on it the first time doesn't trigger the <FocusIn> binding. Is this the wrong binding? Is there something about my lambda function that isn't quite right? Would love some help!
Code:
from tkinter import *
from tkinter import ttk
init_list = ['Mickey', 'Minnie', 'Donald', 'Pluto', 'Goofy']
def db_values():
i = inp_var.get()
db_list = [x for x in init_list if i in x]
print(db_list)
return db_list
def db_refresh(event):
db['values'] = db_values()
root = Tk()
title_label = Label(root, text="Partial string example")
title_label.grid(column=0, row=0)
inp_var = StringVar()
input_box = Entry(root, textvariable=inp_var)
input_box.grid(column=0, row=1)
name_selected = StringVar()
db = ttk.Combobox(root, textvariable=name_selected)
db['values'] = db_values()
db.bind('<FocusIn>', lambda event: db_refresh(event))
db.grid(column=0, row=2, sticky=EW, columnspan=3, padx=5, pady=2)
root.mainloop()

def db_values():
i = inp_var.get()
db_list = [x for x in init_list if i in x]
print(db_list)
db['values'] = db_values()
Only this small Change is requires. list value must be assigned in the function itself.

Related

tkinter, save the input as variable

I want to use the input value as variable and this is my code.
from tkinter import *
from tkinter import messagebox
window = Tk()
Label(window, text='Cavity number').grid(row=0)
CavNum = StringVar()
for i in range(1,8) :
globals()['L{}_CavNum'.format(i)] = StringVar()
globals()['L{}_CavNum'.format(i)] = Entry(window, textvariable=globals()['L{}_CavNum'.format(i)])
globals()['L{}_CavNum'.format(i)].grid(row=0, column=i)
window.geometry("1200x150")
window.mainloop()
everytime I do print(L1_CavNum), it says "<tkinter.Entry object .!entry>". please tell me what is the problem
You are re-using the same name for the entry widget as you use for StringVar. You could simply change globals()['L{}_CavNum'.format(i)] = StringVar() to globals()['L{}_CavNumSV'.format(i)] = StringVar() and print(L1_CavNum) to print(L1_CavNumSV.get()). However the .get() function will execute when your code runs so you will have to have a button or another event to callback the function.
I would do it like this.
from tkinter import *
def print_vars():
for x in range(len(cavity_string_vars)):
print(cavity_string_vars[x].get())
window = Tk()
Label(window, text='Cavity number').grid(row=0)
cavity_string_vars = []
cavity_entries = []
for i in range(7):
cavity_string_vars.append(StringVar())
cavity_entries.append(Entry(window, textvariable=cavity_string_vars[i]))
cavity_entries[i].grid(row=0, column=i)
print_button = Button(window, text="Print", command=print_vars)
print_button.grid(row=1, column=0)
window.geometry("1200x150")
window.mainloop()
To me associated arrays are much easier than naming each variable even when you program it as you have. Perhaps that is needed for your case.

Tkinter Accessing Variables from Different Function

Is there a way to access variables from different files if the widget is an Entry? I have tried using the command option but found that was exclusive to Buttons. I'm trying to separate my functions into different files to modulate.
ttk.Label(root, text="How many points do you want to input:").pack()
cell_content = StringVar()
cell_content.trace_add("write", my_tk.retrieve_cell_content)
cell_content_entry = Entry(root, width = 8, textvariable = cell_content)
cell_content_entry.pack()
tkinterFunctions.py
def retrieve_cell_col(self, *args):
global CELL_COL
temp = cell_col.get()
temp = temp.upper()
If I get it right, you want to get your text in Entry widget when it is writing. Not by pushing a Button. please check this if I am right:
from tkinter import *
def call(tex):
print(tex.get())
root = Tk()
tx = StringVar()
tx.trace("w", lambda name, index, mode, tex=tx: call(tex))
entry = Entry(root, textvariable=tx)
entry .pack()
root.mainloop()

Radiobutton not updating values when clicked in python with tkinter

This is my first attempt at a GUI. Right now I just want to be able to click a radiobutton and make it print the value I assigned to the button. However, var.get() isn't giving me anything. I tried it with IntVar (and had my values as 1 and 2 instead of "proton" and "electron") and var.get() would just give me 0. With StringVar it gives nothing (nothing prints when choosecharge is called by the radiobutton). I've tried reading stuff about radiobuttons and I wrote my code based on how I saw it done and it successfully creates the radiobuttons, but the whole point is to be able to use their values when clicked.
import tkinter as tk
def choosecharge():
print(var.get())
root = tk.Tk()
var = tk.StringVar()
proton = tk.Radiobutton(root, text = "proton", variable = var, value = "proton", command = choosecharge)
proton.pack( )
electron = tk.Radiobutton(root, text="electron", variable = var, value= "electron", command = choosecharge)
electron.pack( )
root.mainloop()
I have taken a slightly different approach to accomplish this task.
I created a dictionary of the integer radiobutton values as key and
the string that you wish to print as value.
Used a label widget to print the string in the GUI
import tkinter as tk
root = tk.Tk()
# define an IntVar
var = tk.IntVar()
# create a dictionary of key:value pair as radiobutton_value: str_name_to_print
values = {1: "proton", 2: "electron"}
# instantiate a label widget
lbl = tk.Label(root)
def choosecharge():
# update the label widgets using the dictionary
lbl.config(text=values[var.get()])
proton = tk.Radiobutton(root, text="proton", variable=var, value=1, command=choosecharge)
proton.pack(anchor=tk.W)
electron = tk.Radiobutton(root, text="electron", variable=var, value=2, command=choosecharge)
electron.pack(anchor=tk.W)
# pack the label widget below the two radiobuttons
lbl.pack()
root.mainloop()
Screenshot
I have commented the lines in the code for better understanding. I hope this solution helps you.

Determining what radiobutton was selected tkinter

I am trying to figure out how to use tkinter radio-buttons properly.
I have used this question as a guideline: Radio button values in Python Tkinter
For some reason I can't figure out how to return a variable that is indicative of what the user selected.
Code:
def quit_loop():
global selection
selection = option.get()
root.quit()
return selection
def createWindow():
root = Tk()
root.geometry=('400x400')
option = StringVar()
option.set('none')
R1 = Radiobutton(root, text='Compile', value = 'Compile', var=option)
R2 = Radiobutton(root, text='Create', value = 'Create', var=option)
button = Button(root, text='ok', command=quit_loop)
R1.pack()
R2.pack()
button.pack()
root.mainloop()
when I call createWindow() I would expect the radio-button box to pop up, and after making my selection and pressing 'ok' I expected it to return me a variable selection which relates to the selected button. Any advice? Tkinter stuff is particularly challenging to me because it seems so temperamental.
You need to make option global if you want to access outside of createWindow
Here's an example of your code that will print out the value of the selected radiobutton and then quit when you click the button. I simply had to declare root and options as global:
from tkinter import *
def quit_loop():
global selection
selection = option.get()
root.quit()
return selection
def createWindow():
global option, root
root = Tk()
root.geometry=('400x400')
option = StringVar()
option.set('none')
R1 = Radiobutton(root, text='Compile', value = 'Compile', var=option)
R2 = Radiobutton(root, text='Create', value = 'Create', var=option)
button = Button(root, text='ok', command=quit_loop)
R1.pack()
R2.pack()
button.pack()
root.mainloop()
createWindow()
As far as I know one needs to do two things to communicate with tkinter
widgets: pass a variable, and pass a command. When user interacts with
widgets, tkinter will do two things: update value of variable and call the
function passed in as command. It is up to us to access the value of the
variable inside the command function.
import tkinter as tk
from tkinter import StringVar, Radiobutton
def handle_radio():
print(option.get())
root = tk.Tk()
option = StringVar()
option.set('none')
R1 = Radiobutton(root, text='Compile', value = 'Compile', var=option, command=handle_radio)
R2 = Radiobutton(root, text='Create', value = 'Create', var=option, comman=handle_radio)
R1.pack()
R2.pack()
root.mainloop()
The code prints 'Create' and 'Compile' when user selects the appropriate
radio option.
Hope this helps.
Regards,
Prasanth

How to get values of checkbuttons from for loop tkinter python

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()

Categories