AaronJPung
AaronJPung

Reputation: 1132

Eliminating AttributeError: 'tuple' object has no attribute 'focus_set' (Python 2.7)

Using Python 2.7, I have built a GUI using Tkinter. On my GUI, I have a button to open an input popup box. The call to the popup box is:

if analysistype == 'Line of sight':
    d = MyDialog(root)

and the popup box is constructed as:

class MyDialog(tkSimpleDialog.Dialog):
    def body(self, master):
        Label(master, text="Things").grid(row=0, columnspan=2)
        Label(master, text="Thing 1").grid(row=1)
        Label(master, text="Thing 2").grid(row=2)

        self.t1 = Entry(master)
        self.t2 = Entry(master)

        thing1 = self.t1.grid(row=1, column=1)
        thing2 = self.t2.grid(row=2, column=1)

        return thing1, thing2

Before entering anything in the popup box, I'm getting an error; full stack trace is as shown (separated into lines, so it's not just a mash of text):

Exception in Tkinter callback

Traceback (most recent call last):

File "C:\Users\ajpung\AppData\Local\Continuum\Anaconda2\lib\lib-tk\Tkinter.py", line 1536, in call return self.func(*args)

File "directory/ThingFinder.py", line 547, in fetch_data thing1 = MyDialog(root)

File "C:\Users\ajpung\AppData\Local\Continuum\Anaconda2\lib\lib-tk\tkSimpleDialog.py", line 81, in init self.initial_focus.focus_set()

AttributeError: 'tuple' object has no attributeattribute 'focus_set'

If I comment out the "return thing1, thing2" line, I do not get this error. However, I still need to return the variables from my popup box. Why is this happening?

Upvotes: 1

Views: 1282

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385940

The body method is supposed to return the widget that should be given focus. This is why you get the error that you get: tkinter is trying to give focus to what is supposed to be a widget, but is instead a tuple. In your case, you probably want to return self.t1

To be able to get the value of the dialog, you need to define the method apply which should save the values to self.result. You can then query the result when the dialog is dismissed.

d = MyDialog(root)
root.wait_window(d.top)
print("the value is %s" % d.result)

A more complete example is here: http://effbot.org/tkinterbook/tkinter-dialog-windows.htm

Upvotes: 2

Related Questions