只允许在tkinter中选择一个RadioButton

时间:2015-11-23 03:41:03

标签: python-3.x tkinter radio-button

我在Tkinter中有一些RadioButtons(Python 3)。这些是btOrangebtPurple。我需要确保一次只能选择其中一个。我怎么能这样做?

我的代码:

from tkinter import *

class MyPaint:

    color = "Black"

    def __init__(self):
        window = Tk()


        self.canvas = Canvas(window, width = 750, height = 500, bg = "white")
        self.canvas.pack()

        colorFrame = Frame(window)
        colorFrame.pack()

        btOrange = Radiobutton(colorFrame, text = "Orange", bg = "Orange", command = self.setColor("Orange"))
        btPurple = Radiobutton(colorFrame, text = "Purple", bg = "Purple", command = self.setColor("Purple"))

1 个答案:

答案 0 :(得分:1)

通过让两个或多个单选按钮共享一个变量,将它们绑在一起。例如:

self.colorVar = StringVar()
btOrange = Radiobutton(..., variable=self.colorVar, value="Orange")
btPurple = Radiobutton(..., variable=self.colorVar, value="Purple")

在这种情况下,self.colorVar将自动设置为选择的单选按钮。