Diogo Daniel
Diogo Daniel

Reputation: 27

I don't understand the difference between these two lines of code

I've written this code in two different ways. Only the second one works, but I don't get why.

1:

buttons = Frame(calculator, bg="green", width=200, height=400).grid()
buttons.columnconfigure(0)

2:

buttons = Frame(calculator, bg="green", width=200, height=400)
buttons.grid()
buttons.columnconfigure(0)

Upvotes: 1

Views: 78

Answers (3)

bruno desthuilliers
bruno desthuilliers

Reputation: 77902

This:

buttons = Frame(calculator, bg="green", width=200, height=400).grid()
  1. creates a Frame object,
  2. calls .grid() on it,
  3. bind the result of the call to .grid() to the name buttons
  4. discards the Frame object

while this:

buttons = Frame(calculator, bg="green", width=200, height=400)
buttons.grid()
  1. creates a Frame() object and binds it to the name button
  2. calls .grid() on the Frame() object and discards the result of this call.

So those two snippets are obviously not equivalent. In the first one, buttons is whatever Frame().grid() returned (seems that it's None actually), in the second, buttons is a Frame() object.

If you want to decompose your first statement, you need an intermediate variable (not buttons) to reference the Frame() object and call grid() on this variable:

frame = Frame(calculator, bg="green", width=200, height=400)
buttons = frame.grid()

Upvotes: 2

youssef
youssef

Reputation: 65

it is the same!, you can do that too!

buttons = Frame(calculator, bg="green", width=200, height=400).grid().columnconfigure(0)

you can use multi methods per a line

Upvotes: 1

Jose A. García
Jose A. García

Reputation: 888

As I said in the comment I hope this little code will let you understand the problem.

class Person:
    def __init__(self, name):
        self.name = name

    def greet(self):
        pass

Joe = Person("Joe")
Joe.greet()

Pet = Person("Pet").greet()

print(Joe)
print(Pet)

The output:

<__main__.Person object at 0x7f1020983080>
None

The problem you have is that Frame constructor returns an object of type Frame while grid method does not return anything. That's why you have the NoneType error.

Upvotes: 8

Related Questions