如何在 Tkinter 中獲得單選按鈕輸出?


Tkinter 中的單選按鈕小部件允許使用者僅從給定選項中選擇一個選項。單選按鈕只有兩個值,真或假。

如果我們想要獲得輸出以檢查使用者已經選擇了哪個選項,那麼我們可以使用 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 selected the option " + 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()

輸出

執行上述程式碼將顯示一個視窗,其中包含一組單選按鈕。單擊任意選項,它將顯示您已經選擇的選項。

更新於: 05-Aug-2021

10K+ 瀏覽量

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.