Reputation: 13
I have used this Tkinter Combobox for getting a value from the user. It does the same and after getting the user input, the selected value is not assigned to that variable. And the twist is, it is an empty STRING. How can I assign the selected value to a variable as a FLOAT?
My CODE:
from tkinter import *
from tkinter.ttk import *
window = Tk()
window.geometry('350x200')
combo = Combobox(window)
combo['values']= (1, 2, 3, 4, 5, 6)
f11=combo.current(1)
combo.grid(column=0, row=0)
window.mainloop()
I need to get the user input value to be assigned to f11 and add it with 50.
Note: I have tried this:f1=float(f11), but it throws an error of ValueError: could not convert string to float: ''
Thanks in advance for your timely help..
Upvotes: 1
Views: 265
Reputation: 46669
Use a DoubleVar()
for the textvariable
option of Combobox()
:
from tkinter import *
from tkinter.ttk import *
window = Tk()
window.geometry('350x200')
f11 = DoubleVar()
combo = Combobox(window, textvariable=f11)
combo['values']= (1, 2, 3, 4, 5, 6)
combo.grid(column=0, row=0)
combo.current(1)
val = f11.get()
print(val, type(val))
window.mainloop()
And the output in console:
2.0 <class 'float'>
Another example to show the value of the variable inside a callback:
from tkinter import *
from tkinter.ttk import *
window = Tk()
window.geometry('350x200')
f11 = DoubleVar()
combo = Combobox(window, textvariable=f11, state="readonly")
combo['values']= (1, 2, 3, 4, 5, 6)
combo.grid(column=0, row=0)
def on_change(event):
val = f11.get()
print(val, type(val))
combo.bind("<<ComboboxSelected>>", on_change)
combo.current(0)
window.mainloop()
The value selected will be shown in console whenever the selection is changed.
Upvotes: 1