How to get the value of radiobutton in Tkinter? - python

I'd like to get the value as text and not integer on my raddiobutton.
I have a frame, named "printers_frame" in which I created radio buttons with a list of printers on the computer of the user.
According to the printer choosen (radiobutton), I will print files on this specific printer.
I followed this tips but I want to do the same with String, not Integer.
Here is the code to create the radio button:
print_variable = StringVar()
for p in printers:
Radiobutton(printers_frame, text = p[2], variable = print_variable, value = p[2], wraplength=int(WIDTH/3)-10, justify="left", bg=BACKGROUND).pack(side = TOP, anchor = W)
Can you help?
Thanks a lot!

Can't you just take the integer value, and convert it with str()?
You can save that in a variable, and use it however you want.
Hopefully, this helps.
Edit:
Say the value of the RadioButton is RadioButton().
You can just do str(RadioButton).
Edit: You can use the StrVar() function in tkinter. You assign your Radio Button to that variable, and then you can use the value as a string.
Then pass the variable with the string when you are initializing your Radio Button. Pass it to a parameter called variable.
So, your radio button would be:
radio_variable = IntVar()
button = RadioButton(master, ..., variable = radio_variable)
Hopefully this helps!

Related

How to a convert a listbox item's name to a label in Python

For the program that I am required to write up, I need the name of a Listbox item to also be the text in the label. This is the code that I thought would work, but it only configurated the label to be the item's number in the Listbox, not the name:
def openAccount(self):
selectedItem = ltboxSrcUser.curselection()
for item in selectedItem:
rootMainPage.withdraw()
rootOthAccPage.deiconify()
lblOtherUserName.config(text = ltboxSrcUser.curselection())
Can anybody help me out?
The documentation for the listbox shows that curselection returns the index of the selected items, not the values. To get the values you must pass the index to the get method.
def openAccount(self):
selectedItems = ltboxSrcUser.curselection()
if selectedItems:
rootMainPage.withdraw()
rootOthAccPage.deiconify()
index = selectedItems[0]
item = ltboxSrcUser.get(index)
lblOtherUserName.config(text=item)

Is there a way to change a keypress in an entry widget in tkinter?

When I press a key on an entry widget, I want that key to be uppercase. How would I do something like that? Validation just checks if you can press it, but I want the key to be changed when you press it.
This can be achieved by using a StringVar and associating with entry widget and then calling trace on it:
var = StringVar()
e = Entry(root,textvariable=var)
var.trace('w',lambda *args: var.set(var.get().upper()))
Additional:
Can also be expanded to understand better by:
def caps(*args):
text = e.get().upper() # Get the text and uppercase it
e.delete(0,'end') # Remove all the current text
e.insert('end',text) # Insert the upper cased text
var.trace('w',caps)
Also the function can be rewritten in terms of using just var:
def caps(*args):
text = var.get().upper() # Get the text and uppercase it
var.set('') # Remove all the current text
var.set(text) # Insert the current text

How to make each radiobutton unique from the others in tkinter

I have a window in Tkinter that looks like this:
When i click on a button in the first row, it stays. However, when i click on a button in the second row, it unselects the one i chose above.
I want it to be able to only select one option per row. Is there something I'm missing? When it's done, I want to be able to iterate over the rows and get the value of the boxes, but I'm not sure how to do that either.
The code for that section is:
for i in studentList:
Label(left,text=i[0][::]+' ' + i[1][::],fg='black',bg='#dbdbdb',font=('Arial',11,'bold')).grid(row=counter,column=0,pady=13,sticky='news')
P = Radiobutton(right,text='Present',bg='#56ab32',fg='black',value='P'+str(counter),indicatoron = 0,font=('Arial',12,'bold'))
P.grid(row=counter,column=0,pady=10,padx=20,sticky='news')
L = Radiobutton(right,text='Leave',bg='#e6a800',fg='white',indicatoron = 0,value='L'+str(counter),font=('Arial',12,'bold'))
L.grid(row=counter,column=1,pady=10,padx=20,sticky='news')
Radiobutton(right,text='Absent',bg='#bd2900',fg='white',indicatoron = 0,value='A'+str(counter),font=('Arial',12,'bold')).grid(row=counter,column=2,pady=10,padx=20,sticky='news')
counter+=1
Radiobuttons work by assigning two or more radiobuttons the same instance of one of tkinter's special variable objects -- usuallyStringVar or IntVar. This sharing of a variable is what makes a group of radiobuttons work as a set, since the variable can only hold a single value.
Because you aren't assigning a variable, tkinter is using a default variable which is the same for every button. Thus, all buttons are acting as a single set.
To make your code work, each row needs to use it's own instance of StringVar. It would look something like this:
vars = []
for i in studentList:
var = StringVar()
vars.append(var)
...
Radiobutton(right, variable=var, ...)
Radiobutton(right, variable=var, ...)
Radiobutton(right, variable=var, ...)
...
With the above, you can get the choice of each row by getting the value of the variable for that row. For example, the first row would be vars[0].get(), the second row would be vars[1].get() and so on.

Label text changing when dictionary is updated

I'm new to coding and i've been messing around with tkinter.
My labels have text, that is supposed to change when the dictionary values are updated.
An example of my code:
def setit(point, adic,number):
adic[point] = adic[point]+number
dict={'a':4,'b':8,'c':3}
aa=Label(root,text=dict['a']).pack()
bb=Label(root,text=dict['b']).pack()
cc=Label(root,text=dict['c']).pack()
Button(command=setit('a',dict,3)).pack()
When the button is pressed i want both the dictionary and the appropriate Label to update. How would you do that? Preferably without OOP. Thanks!
First of all, there are two problems in your code sample:
1) .pack() returns None, so when you do aa=Label(root,text=dict['a']).pack(), you store None in the variable aa, not the label. You should do:
aa = Label(root,text=dict['a'])
aa.pack()
2) The command option of a button takes a function as argument but you do command=setit('a',dict,3) so you execute the function at the button creation. To pass a function with arguments to a button command, you can use a lambda:
Button(command=lambda: setit('a',dict,3))
Then, to update the label when the value in the dictionary is changed, you can store your labels in a dictionary with the same keys and change the text of the appropriate label with label.configure(text='new value'):
import tkinter as tk
def setit(point, adic, label_dic, number):
adic[point] = adic[point] + number # change the value in the dictionary
label_dic[point].configure(text=adic[point]) # update the label
root = tk.Tk()
dic = {'a': 4, 'b': 8, 'c': 3}
# make a dictionary of labels with keys matching the ones of dic
labels = {key: tk.Label(root, text=dic[key]) for key in dic}
# display the labels
for label in labels.values():
label.pack()
tk.Button(command=lambda: setit('a', dic, labels, 3)).pack()
root.mainloop()
You can use a StringVar instead of specifying the text value. That looks like:
d={'a':StringVar(),'b':StringVar(),'c':StringVar()}
aa=Label(root,textvariable=d['a'])
bb=Label(root,textvariable=d['b'])
cc=Label(root,textvariable=d['c'])
aa.pack()
bb.pack()
cc.pack()
And then whenever you want to change the label, you can do
d['a'].set("new text!")
See here for more info on labels.
Note: dict is a reserved word in python, so it's best to not use that as the name of your variable. Same goes for str, int, etc.

Change Listbox items based on selection in another Listbox

I am trying to dynamically change the entries in a Listbox (lb_ledgers) depending on the selection in another Listbox (lb_book). I currently have the following lines of code:
lb_book.bind('<<ListboxSelect>>', onselect)
def onselect(evt):
w = evt.widget
index = int(w.curselection()[0])
value = w.get(index)
The problem is that I do not know how to pass the first Listbox (lb_ledgers) to the function onselect in order to change its contents. I have tried using a lambda construct, but that did not work. Could you please let me know how to solve this?
Thanks,
MiddleClassMan

Categories

Resources