You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter即时购物车开发:如何在单选按钮外获取文本值

解决Tkinter购物车单选按钮的两个问题

一、获取选中单选按钮的商品名称

有两种简单可行的实现方法:

方法1:用字典做价格与名称的映射

先定义一个包含商品价格和对应名称的字典,将价格设为Radiobutton的value,后续拿到选中的价格后,直接从字典中取出对应的名称:

import tkinter as tk

root = tk.Tk()
root.title("购物车")

# 定义商品字典:键为价格,值为商品名称
products = {5.99: "Mango", 3.49: "Apple", 4.99: "Banana"}
selected_price = tk.DoubleVar()

# 创建单选按钮
for price, name in products.items():
    tk.Radiobutton(
        root,
        text=name,
        variable=selected_price,
        value=price
    ).pack(pady=2)

cart_items = []
total = 0.0

def add_to_cart():
    global total
    price = selected_price.get()
    # 通过价格从字典中获取商品名称
    name = products[price]
    cart_items.append((name, price))
    total += price
    # 更新收据和总金额显示
    receipt_text.delete(1.0, tk.END)
    for idx, (item_name, item_price) in enumerate(cart_items, 1):
        receipt_text.insert(tk.END, f"{idx}.) {item_name}: {item_price:.2f}\n")
    total_label.config(text=f"总金额: {total:.2f}")

tk.Button(root, text="加入购物车", command=add_to_cart).pack(pady=5)
receipt_text = tk.Text(root, width=30, height=10)
receipt_text.pack(pady=5)
total_label = tk.Label(root, text="总金额: 0.00")
total_label.pack(pady=2)

root.mainloop()

方法2:直接将商品元组作为Radiobutton的value

Tkinter的变量支持存储元组类型,所以可以把商品名称和价格打包成元组作为value,选中后直接获取元组就能同时拿到两个信息:

import tkinter as tk

root = tk.Tk()
root.title("购物车")

# 定义商品列表:每个元素是(名称, 价格)的元组
products = [("Mango", 5.99), ("Apple", 3.49), ("Banana", 4.99)]
selected_item = tk.Variable()  # 使用通用Variable存储元组

# 创建单选按钮
for name, price in products:
    tk.Radiobutton(
        root,
        text=name,
        variable=selected_item,
        value=(name, price)
    ).pack(pady=2)

cart_items = []
total = 0.0

def add_to_cart():
    global total
    # 直接获取选中的(名称, 价格)元组
    name, price = selected_item.get()
    cart_items.append((name, price))
    total += price
    # 更新收据和总金额显示
    receipt_text.delete(1.0, tk.END)
    for idx, (item_name, item_price) in enumerate(cart_items, 1):
        receipt_text.insert(tk.END, f"{idx}.) {item_name}: {item_price:.2f}\n")
    total_label.config(text=f"总金额: {total:.2f}")

tk.Button(root, text="加入购物车", command=add_to_cart).pack(pady=5)
receipt_text = tk.Text(root, width=30, height=10)
receipt_text.pack(pady=5)
total_label = tk.Label(root, text="总金额: 0.00")
total_label.pack(pady=2)

root.mainloop()

二、单个Radiobutton是否支持绑定两个变量?

单个Radiobutton不支持直接绑定两个独立的Tkinter变量,它的variable参数只能指定一个变量来存储选中的值。但可以通过上面两种方法,将多个数据(名称+价格)打包成一个值(元组或通过字典映射),间接实现同时获取多个信息,效果和绑定两个变量一致。

内容的提问来源于stack exchange,提问作者Leah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 20:33:35