Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chỉ cho chọn một Radiobutton trong Tkinter

Radiobutton widget cho phép chọn một option từ tập choices. Giá trị Boolean: True/False.

Dùng IntVar() chung cho group. get() trả về value của option được chọn.

Ví dụ

from tkinter import *
from tkinter import ttk

win = Tk()
win.geometry("700x350")

def selection():
    selected = "You have selected " + str(radio.get())
    label.config(text=selected)

radio = IntVar()
Label(text="Your Favourite programming language:", font=('Aerial 11')).pack()

Radiobutton(win, text="C++", variable=radio, value=1, command=selection).pack(anchor=N)
Radiobutton(win, text="Python", variable=radio, value=2, command=selection).pack(anchor=N)
Radiobutton(win, text="Java", variable=radio, value=3, command=selection).pack(anchor=N)

label = Label(win)
label.pack()
win.mainloop()

Kết quả

3 Radiobutton C++, Python, Java. Chọn 1 → Label hiển thị "You have selected [1/2/3]".

Chỉ cho chọn một Radiobutton trong Tkinter

Lưu ý: Cùng variable=radio đảm bảo chỉ chọn 1. Dùng StringVar() với value="cpp"/"python"/"java" để lấy string trực tiếp.