問題描述
Tkinter 組合框 Python (Tkinter Combobox Python)
我使用這個 Tkinter Combobox 從用戶那裡獲取一個值。它的作用相同,在獲得用戶輸入後,所選值不會分配給該變量。扭曲的是,它是一個空字符串。如何將所選值作為 FLOAT 分配給變量?
我的代碼:
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()
我需要獲取要分配的用戶輸入值到 f11 並添加 50。
注意:我試過這個:f1=float(f11),但它會拋出 ValueError 錯誤:無法將字符串轉換為浮點數:''
提前感謝您的及時幫助..
參考解法
方法 1:
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.
(by SANNASI CHAKRAVARTHY、acw1668)