如何在 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()
输出
执行上述代码将显示一个窗口,其中包含一组单选按钮。单击任意选项,它将显示您已经选择的选项。
广告