Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Tkinter에서 하나의 라디오 버튼만 선택하는 방법은 무엇입니까?

<시간/>

하나 이상의 옵션에 대한 선택을 구현하기 위해 Radiobutton 위젯을 사용할 수 있습니다. Tkinter의 Radiobutton 위젯을 사용하면 사용자가 주어진 선택 항목 집합에서 하나의 옵션만 선택할 수 있습니다. 라디오 버튼에는 True 또는 False의 두 가지 부울 값만 있습니다.

사용자가 선택한 옵션을 확인하기 위한 출력을 얻으려면 get()을 사용할 수 있습니다. 방법. 변수로 정의된 객체를 반환합니다. 문자열 개체의 정수 값을 캐스팅하여 레이블 위젯에 선택 항목을 표시하고 텍스트 속성에 전달할 수 있습니다.

예시

# Import the required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame or window
win = Tk()

# Set the size of the window
win.geometry("700x350")


# Define a function to get the output for selected option
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()

# Define radiobutton for each options
r1 = Radiobutton(win, text="C++", variable=radio, value=1, command=selection)
r1.pack(anchor=N)

r2 = Radiobutton(win, text="Python", variable=radio, value=2, command=selection)
r2.pack(anchor=N)

r3 = Radiobutton(win, text="Java", variable=radio, value=3, command=selection)
r3.pack(anchor=N)

# Define a label widget
label = Label(win)
label.pack()

win.mainloop()

출력

위의 코드를 실행하면 레이블 위젯과 옵션에 해당하는 라디오 버튼 세트가 있는 창이 표시됩니다. 출력을 보려면 목록에서 옵션을 선택하십시오.

Tkinter에서 하나의 라디오 버튼만 선택하는 방법은 무엇입니까?