攝影或3C

Python: 如何用tkinter做出Listbox列表選擇框 GUI? menu = tk.StringVar(root, value= tuple( cable.items() ) ) ; listbox = tk.Listbox (root, listvariable = menu)

本文參考STEAM教育學習網

# -*- coding: utf-8 -*-
"""
Created on Wed Jun  6 18:03:38 2023

@author: SavingKing
"""

import tkinter as tk
root=tk.Tk()
root.title("listbox by SavingKing.com.tw")
root.geometry("350x300")

listbox=tk.Listbox(root)
listbox.insert(1,"SavingKing")
listbox.insert(2,"賴:@wvr5039s")
listbox.insert(3,"儲蓄保險王")
listbox.pack()

root.mainloop()

GUI:

使用tk.END

使用StringVar 與 listvariable

# -*- coding: utf-8 -*-
"""
Created on Wed Jun  6 18:03:38 2023

@author: SavingKing
"""

from typing import Dict,Tuple

cable:Dict[str,Tuple[float]] = {
    "UFA125A": (13.95, 0.4), 
    "UED240E": (8.09, 0.76)}

import tkinter as tk
root=tk.Tk()
root.title("listbox by SavingKing.com.tw")
root.geometry("350x300")

menu = tk.StringVar(root, tuple(cable.items()) )
"""#不要漏掉root參
tuple(cable.keys())
Out[61]: ('UFA125A', 'UED240E')
tuple(cable.items())
Out[67]: (('UFA125A', (13.95, 0.4)), ('UED240E', (8.09, 0.76)))
"""

listbox=tk.Listbox(root,listvariable=menu)

listbox.pack()

root.mainloop()

GUI:

listbox.curselection()
#取得listbox 項目 含索引值的tuple #(1,)
listbox.get(n) #獲得該索引值的內容

# -*- coding: utf-8 -*-
"""
Created on Wed Jun  6 18:03:38 2023

@author: SavingKing
"""

from typing import Dict,Tuple

cable:Dict[str,Tuple[float]] = {
    "UFA125A": (13.95, 0.4), 
    "UED240E": (8.09, 0.76)}

import tkinter as tk
root=tk.Tk()
root.title("listbox by SavingKing.com.tw")
root.geometry("350x300")

# 定義 Label 顯示選取內容的函式
def show():
    n, = listbox.curselection()  
    # 取得項目索引值因為是單選回傳 (i,),所以使用 n, 取值
    text.set(listbox.get(n))     
    # 設定文字變數內容為該索引值對應的內容

text = tk.StringVar()            # 設定文字變數
#默認第一個參數為root
label = tk.Label(root, textvariable=text)  # 放入 Label
label.pack()

menu = tk.StringVar(root, tuple(cable.items()) )
"""#因為有第二個參數value=tuple,不可省略第一個root參數,
不然會把tuple當成root,觸發AttributeError:
 'tuple' object has no attribute '_root'

tuple(cable.keys())
Out[61]: ('UFA125A', 'UED240E')
tuple(cable.items())
Out[67]: (('UFA125A', (13.95, 0.4)), 
          ('UED240E', (8.09, 0.76)))
tk.Entry(root,textvariable=tk.StringVar(value="2"))
"""
listbox=tk.Listbox(root,listvariable=menu)
listbox.pack()

btn = tk.Button(root, text='顯示', command=show)  
# 放入 Button設定 command 參數
btn.pack()

root.mainloop()

tk.StringVar?

menu = tk.StringVar(root, tuple(cable.items()) )
“””#因為有第二個參數value=tuple,
不可省略第一個root參數,
不然會把tuple當成root,觸發AttributeError:
‘tuple’ object has no attribute ‘_root’ “””

GUI:

listbox GUI

推薦hahow線上學習python: https://igrape.net/30afN

儲蓄保險王

儲蓄險是板主最喜愛的儲蓄工具,最喜愛的投資理財工具則是ETF,最喜愛的省錢工具則是信用卡