1

I'm trying to give the user a set of choices using radio buttons. When I click on the "Get Data Type" button, Python returns "AttributeError: Radiobutton instance has no attribute 'variable'. Clearly it does, but refuses to see it (them):

class DataType:

    def __init__(self, master):
        frame = LabelFrame(master, text = 'Data Type')
        frame.pack()

        data_contents = StringVar()

        self.radiobutton = Radiobutton(frame,
                     text="Fixed Data",
                     variable = data_contents,
                     value = 'fixed')
        self.radiobutton.pack()

        self.radiobutton = Radiobutton(frame,
                     text="Random Data",
                     variable = data_contents,
                     value = 'random')
        self.radiobutton.pack()

        self.radiobutton = Radiobutton(frame,
                     text="All 1's",
                     variable = data_contents,
                     value = '1s')
        self.radiobutton.pack()

        self.radiobutton = Radiobutton(frame,
                     text="All 0's",
                     variable = data_contents,
                     value = '0s')
        self.radiobutton.pack()


        data_contents.set(self.radiobutton)
        self.printdata = Button(frame,
                         text="What data?",
                         command=self.write_data)
        self.printdata.pack()

    def write_data(self):
        print (self.radiobutton.variable)
4

1 回答 1

0

You are misunderstanding tkinter options. When you specify an attribute like variable=data_contents, it does not become an attribute of the object. Instead, it is a widget configuration option.

To access the value of the variable configuration option you need to use one of the following:

self.radiobutton.cget("variable")
self.radiobutton["variable"]

Note: you are headed down the wrong path with this question. You don't need to get the variable since you control what the variable is. The variable should be an instance attribute that you can call the get() method on:

...
self.data_contents = StringVar()
...
def write_data(self):
    print(self.data_contents.get())
于 2015-05-27T16:37:54.820 回答