Tkinter的Radiobutton组件

2022-10-08,,

radiobutton:单选按钮

一、基本使用

程序效果,打印选中菜的价格。

代码1如下:

# coding:utf8
from tkinter import *
# 点击按钮打印蔬菜价格


class app:
    def __init__(self, master):
        dict1 = {1: 2, 2: 3, 3: 4, 4: 5}
        frame = frame(master, width=200, height=100)
        frame.pack()
        # 设置默认值为1,默认青菜被选中
        v = intvar()
        v.set(1)
        radiobutton(frame, text="青菜", variable=v, value=1).pack()
        radiobutton(frame, text="白菜", variable=v, value=2).pack()
        radiobutton(frame, text="菠菜", variable=v, value=3).pack()
        radiobutton(frame, text="黄瓜", variable=v, value=4).pack()

        # 触发事件
        def show():
            key = v.get()
            print("您选中菜的价格为: %d 元" % dict1[key])
            return true
        button(frame, text="点击查看价格", command=show).pack()


root = tk()
win = app(root)
root.mainloop()

代码2如下:

使用字典循环生成单选,如果价格不重复的话,可以用价格来指定value的值。

如果价格重复,那么选中这个,另一个也会选中,这时就需要另一个变量来代替了,也需要再加一个字典。

字典1:菜名:序号;字典2:序号:价格

# coding:utf8
from tkinter import *
# 点击按钮打印蔬菜价格


class app:
    def __init__(self, master):
        dict1 = {"青菜": 2, "白菜": 3, "菠菜": 4, "黄瓜": 5}
        frame = frame(master, width=200, height=100)
        frame.pack()
        v = intvar()
        v.set(dict1["青菜"])
        for i in dict1:
            radiobutton(frame, text=i, variable=v, value=dict1[i]).pack()

        # 触发事件
        def show():
            key = v.get()
            print("您选中菜的价格为: %d 元" % key)
            return true
        button(frame, text="点击查看价格", command=show).pack()


root = tk()
win = app(root)
root.mainloop()

读书和健身总有一个在路上

《Tkinter的Radiobutton组件.doc》

下载本文的Word格式文档,以方便收藏与打印。