Radiobutton component of Tkinter

Radiobutton: radio button

1, Basic use

Program effect, print the price of the selected dish.

Code 1 is as follows:

# coding:utf8
from tkinter import *
# Click the button to print the price of vegetables


class App:
    def __init__(self, master):
        dict1 = {1: 2, 2: 3, 3: 4, 4: 5}
        frame = Frame(master, width=200, height=100)
        frame.pack()
        # Set the default value to 1, and the default green vegetables are selected
        v = IntVar()
        v.set(1)
        Radiobutton(frame, text="Greens", variable=v, value=1).pack()
        Radiobutton(frame, text="Chinese cabbage", variable=v, value=2).pack()
        Radiobutton(frame, text="Spinach", variable=v, value=3).pack()
        Radiobutton(frame, text="cucumber", variable=v, value=4).pack()

        # Trigger event
        def show():
            key = v.get()
            print("The price of your choice is: %d element" % dict1[key])
            return True
        Button(frame, text="Click to view the price", command=show).pack()


root = Tk()
win = App(root)
root.mainloop()

Code 2 is as follows:

Use the dictionary loop to generate radio options. If the price is not repeated, you can use the price to specify the value.

If the price is repeated, then select this one and the other one will be selected. At this time, another variable is needed to replace it and another dictionary is also needed.

Dictionary 1: dish name: serial number; dictionary 2: serial number: price

# coding:utf8
from tkinter import *
# Click the button to print the price of vegetables


class App:
    def __init__(self, master):
        dict1 = {"Greens": 2, "Chinese cabbage": 3, "Spinach": 4, "cucumber": 5}
        frame = Frame(master, width=200, height=100)
        frame.pack()
        v = IntVar()
        v.set(dict1["Greens"])
        for i in dict1:
            Radiobutton(frame, text=i, variable=v, value=dict1[i]).pack()

        # Trigger event
        def show():
            key = v.get()
            print("The price of your choice is: %d element" % key)
            return True
        Button(frame, text="Click to view the price", command=show).pack()


root = Tk()
win = App(root)
root.mainloop()


There is always one on the way to study and keep fit

Tags: Python

Posted on Wed, 06 May 2020 10:56:51 -0400 by s.prema@yahoo.com