3

I have a problem with tkinter regarding separating UI and UI functionality in two modules,here is my code:

1-view.py

from tkinter import *

class View():
    def __init__(self,parent):
        self.button=Button(parent,text='click me').pack()

2.controller.py

from tkinter import *
from view import *

class Controller:
    def __init__(self,parent):
        self.view1=View(parent)
        self.view1.button.config(command=self.callback)

    def callback(self):
        print('Hello World!')


root=Tk()
app=Controller(root)
root.mainloop()

on running controller.py I get the following error:

AttributeError: 'NoneType' object has no attribute 'config'

any suggestion?

also I tried to use lambda for using a callback function in another module but it didn't work.

thanks in advance

2 Answers 2

2

the lambda approach problem was exactly as above which is now resolved by using the pack in a new line. it seems more beautiful, here is the sample using lambda which is working fine:

1.view.py

from tkinter import *
from controller import *

class View():
    def __init__(self,parent):
        button=Button(parent,text='click me')
        button.config(command=lambda : callback(button))
        button.pack()


root=Tk()
app=View(root)
root.mainloop()

2.controller.py

def callback(button):
    button.config(text='you clicked me!')
    print('Hello World!')

using this approach we can move all functionality away from UI and make it clean and readable.

Sign up to request clarification or add additional context in comments.

Comments

1

In view.py you are calling:

self.button=Button(parent,text='click me').pack()

The pack function doesn't return the Button object that you want to assign to self.button, which causes the AttributeError later on. You should do:

self.button = Button(parent, text='click me')
self.button.pack()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.