Tkinter 組合框 Python (Tkinter Combobox Python)


問題描述

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

參考文件

  1. Tkinter Combobox Python (CC BY‑SA 2.5/3.0/4.0)

#Combobox #Variables #Python #user-interface #tkinter






相關問題

tcl/tk 小部件組合框失去焦點 (tcl/tk widget combobox loses focus)

Flex Combobox 奇怪的問題 (Flex Combobox strange problem)

在組合框中對齊文本 (Align Text in Combobox)

如何同時綁定到 ComboBox 中的兩個不同的依賴屬性? (How do I bind to two different dependency properties in a ComboBox at the same time?)

在綁定到字典的組合框中設置所選項目 (Setting selected item in combobox bound to dictionary)

easyUI datagrid內部編輯組合框無法選擇默認值 (easyUI datagrid inner edit combobox cannot selected default value)

VBA:數據輸入組合框有效,但命令按鈕給出“無效的屬性值”錯誤 (VBA: Data entry into combobox works, but command button gives "Invalid property value" error)

vb.net - 組合框總是選擇第一個值 (vb.net - combo box always select the first value)

打開 ComboBox DropDown 時不要選擇文本輸入 (Do not select text input when ComboBox DropDown is opened)

如何使用相同的數據源設置多個組合框? (How can I set up multiple combo-boxes with the same data source?)

如何使用 QtreeView 在 QComboBox 中設置所選項目 (How to set selected item in QComboBox with QtreeView)

Tkinter 組合框 Python (Tkinter Combobox Python)







留言討論